更新matplotlib条形图?

问题描述:

我有一个条形图,可从字典中检索其y值.与其显示所有具有不同值的多个图,而不必关闭每个图,我需要它来更新同一图上的值.有解决方案吗?

I have a bar graph which retrieves its y values from a dict. Instead of showing several graphs with all the different values and me having to close every single one, I need it to update values on the same graph. Is there a solution for this?

下面是一个如何制作条形图动画的示例. 您只调用一次plt.bar,保存返回值rects,然后调用rect.set_height修改条形图. 调用fig.canvas.draw()会更新图形.

Here is an example of how you can animate a bar plot. You call plt.bar only once, save the return value rects, and then call rect.set_height to modify the bar plot. Calling fig.canvas.draw() updates the figure.

import matplotlib
matplotlib.use('TKAgg')
import matplotlib.pyplot as plt
import numpy as np

def animated_barplot():
    # http://www.scipy.org/Cookbook/Matplotlib/Animations
    mu, sigma = 100, 15
    N = 4
    x = mu + sigma*np.random.randn(N)
    rects = plt.bar(range(N), x,  align = 'center')
    for i in range(50):
        x = mu + sigma*np.random.randn(N)
        for rect, h in zip(rects, x):
            rect.set_height(h)
        fig.canvas.draw()

fig = plt.figure()
win = fig.canvas.manager.window
win.after(100, animated_barplot)
plt.show()