简体   繁体   English

刷新图形时使用pylab / matplotlib更新标签

[英]updating labels using pylab / matplotlib when refreshing a graph

I have some standard boiler plate code to draw a simple bar graph with a "count" label on top of each bar. 我有一些标准的锅炉板代码,用于在每个条形图的顶部绘制一个带有“计数”标签的简单条形图。 I am live updating this bar graph as the data changes. 随着数据的变化,我正在更新此条形图。 I am able to successfully live update the graph. 我能够成功实时更新图表。 Here is the code : 这是代码:

fig, ax = plt.subplots()
def my_graph():
    y_pos = np.arange(len(data_list))
    rects1 = ax.bar(y_pos, count_list, 0.28, color='r')
    # plt.bar(y_pos, count_list, 0.28, color='b', align='center', alpha=0.5)
    ax.set_xticks(y_pos, data_list)
    ax.set_xticklabels(data_list, rotation='vertical')
    ax.set_ylabel('Counts')
    ax.set_title('Some stats ')
    plt.plot()
    plt.ylim([0, 50])
    autolabel(rects1)

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height,
            '%d' % int(height), ha='center', va='bottom')

which as you can see is standard boiler plate code. 您可以看到标准锅炉板代码。 In my main I do: 在我的主要我做:

if __name__ == "__main__":
    my_graph()
    plt.ion()
    while True:
        time.sleep(3)
        get_updated_data()
        my_graph()
        plt.pause(0.01)

get_updated_data will just pull new data and call the code to generate the graph. get_updated_data将只提取新数据并调用代码生成图形。 This is correctly updating the bars. 这是正确更新栏。 However, the labels added above each bar aren't overwritten. 但是,每个栏上方添加的标签不会被覆盖。 They get "stacked" above each other each time the graph is refreshed. 每次刷新图形时,它们都会“堆叠”在彼此之上。 Whats the appropriate way to fix this ? 什么是解决这个问题的适当方法? I have tried fig.canvas.draw() but it is not working. 我试过fig.canvas.draw()但它没有用。 Maybe I am adding it in the wrong place. 也许我在错误的地方添加它。 Whats the right approach ? 什么是正确的方法?

Thanks 谢谢

One option is to clear the axes each iteration with cla() . 一种选择是使用cla()清除每次迭代的轴。 Alternately you could store each text object and remove them when needed. 或者,您可以存储每个文本对象,并在需要时将其删除。

t = ax.text(0.5,0.5,"label")
plt.pause(3)
t.remove()
fig.canvas.draw()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM