实时更新pyplot图

时间:2017-06-21 20:50:10

标签: python matplotlib time

我试图绘制2D网格数据并将它们映射到颜色。然后我想更新值并使用新值更新图表。目前,图表仅显示最终结果,而不是图表应经历的所有中间阶段。

我的代码::

{{1}}

2 个答案:

答案 0 :(得分:1)

pyplot被调用之前,

pyplot.show()通常不会显示任何内容,除非matplotlib在互动'中运行模式。通过调用pyplot.ion()输入交互模式,并可以通过调用pyplot.ioff()再次退出。

因此,您应该可以在执行任何想要直接更新的内容之前通过调用pyplot.ion()来查看所有更新,然后使用pyplot.ioff()结束您的程序以恢复标准{ {1}}完成后的方式。

但是,它可能看起来不太顺畅,具体取决于您的系统以及您正在进行的更新。

答案 1 :(得分: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