2012-02-28 131 views
4

我有一個條形圖,它從字典中檢索它的y值。我不需要顯示具有所有不同值的幾張圖,也不必關閉每張圖,我需要它在同一個圖上更新值。有沒有解決方案?更新matplotlib條形圖?

回答

8

下面是如何爲條形圖設置動畫的示例。 您只需撥打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() 
0

我已經簡化上述極好地解決了它的本質,更多的細節我blogpost

import numpy as np 
import matplotlib.pyplot as plt 

numBins = 100 
numEvents = 100000 

file = 'datafile_100bins_100000events.histogram' 
histogramSeries = np.fromfile(file, int).reshape(-1,numBins) 

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): 
    [rect.set_height(h) for rect,h in zip(rects,histogramSeries[i,:])] 
    fig.canvas.draw() 
    plt.pause(0.001)