Animating a square from pcolormesh using matplotlib

As a result of a full day of trial and error, I publish my results as helping someone who might run into this problem.

Over the past two days, I have been trying to simulate a real-time graph of some radar data from a netCDF file to work with the graphical interface that I create for a school project. The first thing I tried was a simple redraw of the data using matplotlib "interactive mode" as follows:

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 

While this technically works, it also disables the zoom features, as well as panning and anything else!

For the graph of the radar, this was unacceptable. See My solution below.

+5
source share
1 answer

So, I started learning the matplotlib animation APIs, hoping to find a solution. The animation turned out to be exactly what I was looking for, although its use with the QuadMesh object in slices was not accurately documented. Here is what I came up with:

 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]) 

Note that blit must be False! Otherwise, it will yell at you that the QuadMesh object is not iterable.

I don’t have access to the radar yet, so I couldn’t test it against live data streams, but for a static file it still worked fine. While the data is being built, I can scale and pan the animation.

Good luck with your own animation / graphic ambitions!

+3
source

Source: https://habr.com/ru/post/953814/


All Articles