python
  • python-3.x
  • matplotlib
  • 2017-07-17 102 views 1 likes 
    1

    我有一个使用matplotlib的python 3.x代码。如何在python中编辑表格?

    colLabels = ["Name", "Number"] 
    data = [["Peter", 17], ["Sara", 21], ["John", 33]] 
    the_table = ax.table(cellText=data, 
            colLabels=colLabels, 
            loc='center') 
    plt.pause(0.1) 
    

    上面的代码是在一个循环中,现在我想搜索与第一列“彼得”(这是唯一的)行和编辑它,以便在每次迭代中第二列变化的条目。我可以清除整个ax并添加新表,但它效率低下(我将重新绘制表,每0.1s多行)

    有没有办法在matplotlib(以及如何)中编辑它,或者我应该使用一些其他库(哪一个)?

    +0

    我建议你看看Pandas,它带有表格的Dataframe类型。它具有丰富的编辑功能(也是矢量化的),并且还可以与matplotlib良好地连接。但是,我不知道我是否真的有你的问题。你是否想部分更新展示的情节? – ypnos

    +1

    您是否考虑过使用[Matplotlib动画API](http://matplotlib.org/api/animation_api.html)? – krassowski

    +0

    @ypnos我想编辑'data'里面的内容,看看'the_table'(正在显示的内容)的变化 **编辑**:也是有效的,因为我现在正在做的是删除'the_table'和用更新的'数据'创建一个新的' – Pitirus

    回答

    4

    matplotlib表中的文本可以通过选择单元格并设置单元格的_text属性的文本来更新。例如。

    the_table._cells[(2, 1)]._text.set_text("new text") 
    

    将更新第三行和第二列中的单元格。

    一个动画例子:

    import matplotlib.pyplot as plt 
    from matplotlib.animation import FuncAnimation 
    
    fig, ax = plt.subplots(figsize=(4,2)) 
    colLabels = ["Name", "Number"] 
    data = [["Peter", 1], ["Sara", 1], ["John", 1]] 
    the_table = ax.table(cellText=data, 
            colLabels=colLabels, 
            loc='center') 
    
    def update(i): 
        the_table._cells[(1, 1)]._text.set_text(str(i)) 
        the_table._cells[(2, 1)]._text.set_text(str(i*2)) 
        the_table._cells[(3, 1)]._text.set_text(str(i*3)) 
    
    ani = FuncAnimation(fig, update, frames=20, interval=400) 
    plt.show() 
    

    enter image description here

    找出需要更新其细胞,将可能是最好的使用数据,而不是从表中读取它来完成。

    inx = list(zip(*data))[0].index("Peter") 
    

    为您提供了索引0,使得细胞可以通过 the_table._cells[(inx+1, 1)]访问(注意+1,这是因为表标题的出现)。

    +0

    你知道如何添加一行到这个表吗? – Pitirus

    +1

    你可以使用'the_table.add_cell()',但它可能有点点或工作,以让它很好地显示。 – ImportanceOfBeingErnest

    相关问题