2017-06-21 47 views
1

我試圖繪製一個2D網格數據並將它們映射到顏色。然後,我想更新這些值並使用新值更新圖形。目前該圖只顯示最終結果,並非圖表應該經過的所有中間階段。實時更新pyplot圖

我的代碼::

import matplotlib.pyplot as pyplot 
import matplotlib as mpl 
import numpy as np 
import time 
import matplotlib.animation as animation 



thing=0 
NUM_COL=10 
NUM_ROW=10 

zvals=np.full((NUM_ROW,NUM_COL),-5.0) 

def update_graph(zvals): 
    zvals+=1 
    pyplot.clf() 
    img = pyplot.imshow(zvals,interpolation='nearest', 
        cmap = cmap,norm=norm) 
    time.sleep(1) 
    pyplot.draw() 

# make a color map of fixed colors 
cmap = mpl.colors.ListedColormap(['blue','black','red']) 
bounds=[-6,-2,2,6] 
norm = mpl.colors.BoundaryNorm(bounds, cmap.N) 

# tell imshow about color map so that only set colors are used 

img = pyplot.imshow(zvals,interpolation='nearest', 
        cmap = cmap,norm=norm) 

# make a color bar 
pyplot.colorbar(img,cmap=cmap,norm=norm,boundaries=bounds,ticks=[-5,0,5]) 



pyplot.draw() 

for i in range(5): 
    update_graph(zvals) 

pyplot.show() 

回答

1

pyplot一般不會表現出任何東西,直到pyplot.show()被調用時,除非在 '互動' 模式matplotlib運行。通過調用pyplot.ion()來輸入交互模式,並可以通過調用pyplot.ioff()再次退出。

因此,應該可以讓你通過調用pyplot.ion()地方之前做你想做的直接更新,然後用pyplot.ioff()結束你的程序完成後,回到標準pyplot什麼方式看到您所有的更新。

但是,它看起來可能不是很流暢,這取決於您的系統以及您正在執行的更新。

0

所以我不確定這個回答與否,我只用過一次更新的情節。但這是實現你想要的一種方式。

import matplotlib.animation as animation 
import matplotlib.pyplot as plt 
import matplotlib as mpl 
import numpy as np 

NUM_COL = 10 
NUM_ROW = 10 

zvals = np.full((NUM_ROW,NUM_COL),-5.0) 
cmap = mpl.colors.ListedColormap(['blue','black','red']) 
bounds = [-6,-2,2,6] 
norm = mpl.colors.BoundaryNorm(bounds, cmap.N) 

fig = plt.figure() # Create the figure 
img = plt.imshow(zvals,interpolation='nearest', cmap=cmap,norm=norm) # display the first image 
plt.colorbar(img,cmap=cmap,norm=norm,boundaries=bounds,ticks=[-5,0,5]) # create your colour bar 

# If we dont have this, then animation.FuncAnimation will call update_graph upon initialization 
def init(): 
    pass 

# animation.FuncAnimation will use this function to update the plot. This is where we update what we want displayed 
def update_graph(frame): 
    global zvals # zvals is a global variable 
    zvals+=1 
    img.set_data(zvals) # This sets the data to the new, updated values 
    print("Frame Update {}".format(frame)) # this is for debugging to help you see whats going on 
    return img 

# This is what will run the animations 
anim = animation.FuncAnimation(fig, update_graph, init_func = init, 
                interval = 1000, # update every 1000ms 
                frames = 8, # Update 8 times 
                repeat=False) # After 8 times, don't repeat the animation 
plt.show() # show our plot