更新一个matplotlib条形图?

9

我有一个柱状图,它从字典中获取其y值。我需要它更新同一张图表上的值,而不是显示多个具有所有不同值的图表,然后我必须关闭每个单独的图表。是否有解决方案?

2个回答

14
这是一个如何为柱状图添加动画效果的例子。 你只需要调用plt.bar一次,保存返回值rects,然后调用rect.set_height来修改条形图。 调用fig.canvas.draw()更新图形即可。
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()

如果每次更新需要向图形添加新的柱状图时怎么办?此外,fig.canvas.draw() 与使用 FuncAnimation 相比如何? - Burrito

5

我将上述出色的解决方案简化为其要点,更多细节请参见我博客文章

import numpy as np
import matplotlib.pyplot as plt

numBins = 100
numEvents = 100000

file = 'datafile_100bins_100000events.histogram'
histogramSeries = np.loadtext(file)

fig, ax = plt.subplots()
rects = ax.bar(range(numBins), np.ones(numBins)*40)  # 40 is upper bound of y-axis 

for i in range(numEvents):
    for rect,h in zip(rects,histogramSeries[i,:]):
        rect.set_height(h)
    fig.canvas.draw()
    plt.pause(0.001)

@stochastic 你有没有开始保存动画了? - László
@László 我作弊,用桌面视频,因为我不需要高质量。 - stochashtic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接