繁体   English   中英

更新 matplotlib 条形图?

[英]Updating a matplotlib bar graph?

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

以下是如何为条形图设置动画的示例。 您只调用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()

我已经将上述出色的解决方案简化为它的基本要素,并在我的博客文章中提供了更多详细信息:

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)

暂无
暂无

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

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