2012-02-28 4 views
4

私はdictからそのyの値を取り出す棒グラフを持っています。異なる値を持つ複数のグラフを表示するのではなく、1つのグラフをすべて閉じなければならないのではなく、同じグラフの値を更新する必要があります。これには解決策がありますか?matplotlib棒グラフを更新しますか?

答えて

8

棒グラフをアニメーション表示する方法の例を次に示します。 plt.barを1回だけ呼び出し、戻り値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) 
関連する問題