使用matplotlib从pcolormesh动画化Quadmesh

Mel*_*ict 6 python animation matplotlib

由于一整天的反复试验,我将调查结果发布给任何可能遇到此问题的人.

在过去的几天里,我一直在尝试模拟netCDF文件中某些雷达数据的实时绘图,以便与我正在为学校项目构建的GUI一起工作.我尝试的第一件事是使用matplotlib的"交互模式"简单地重绘数据,如下所示:

import matplotlib.pylab as plt

fig = plt.figure()
plt.ion() #Interactive mode on
for i in range(2,155): #Set to the number of rows in your quadmesh, start at 2 for overlap
    plt.hold(True)
    print i
    #Please note: To use this example you must compute X, Y, and C previously.
    #Here I take a slice of the data I'm plotting - if this were a real-time
    #plot, you would insert the new data to be plotted here.
    temp = plt.pcolormesh(X[i-2:i], Y[i-2:i], C[i-2:i])
    plt.draw()
    plt.pause(.001) #You must use plt.pause or the figure will freeze

 plt.hold(False)      
 plt.ioff() #Interactive mode off
Run Code Online (Sandbox Code Playgroud)

虽然这在技术上有效,但它也会禁用缩放功能,以及平移,以及一切!

对于雷达显示图,这是不可接受的.请参阅下面的解决方案.

Mel*_*ict 3

于是我开始研究matplotlib动画API,希望能找到解决方案。事实证明,该动画确实正是我所寻找的,尽管它在切片中与 QuadMesh 对象的使用并未得到确切记录。这就是我最终想出的:

import matplotlib.pylab as plt
from matplotlib import animation

fig = plt.figure()

plt.hold(True)
#We need to prime the pump, so to speak and create a quadmesh for plt to work with
plt.pcolormesh(X[0:1], Y[0:1], C[0:1])

anim = animation.FuncAnimation(fig, animate, frames = range(2,155), blit = False)

plt.show()
plt.hold(False)

def animate( self, i):
    plt.title('Ray: %.2f'%i)
    #This is where new data is inserted into the plot.
    plt.pcolormesh(X[i-2:i], Y[i-2:i], C[i-2:i])
Run Code Online (Sandbox Code Playgroud)

请注意,blit 必须为 False!否则它会向你大喊 QuadMesh 对象不是“可迭代的”。

我还无法访问雷达,因此我无法针对实时数据流进行测试,但对于静态文件,到目前为止它效果很好。在绘制数据时,我可以使用动画进行缩放和平移。

祝你自己的动画/绘图梦想好运!