I am trying to animate a pcolormesh
in matplotlib
. I have seen many of the examples using the package animation, most of them using a 1D plot routine, and some of them with imshow()
.
First, I wan to use the FuncAnimation routine
. My problem is, first, that I do not know if I can initialize the plot
fig,ax = plt.subplots()
quad = ax.pcolormesh(X,Y,Z)
I have tried a few simple lines:
fig,ax = plt.subplots()
quad = ax.pcolormesh([])
def init():
quad.set_array([])
return quad,
def animate(ktime):
quad.set_array(X,Y,np.sin(Z)+ktime)
return quad,
anim = animation.FuncAnimation(fig,animate,init_func=init,frames=Ntime,interval=200,blit=True)
plt.show()
By the way, How do I set labels into and animated plot? Can I animate the title, if it is showing a number that changes in time? Thanks
I am not sure why your quad = ax.pcolormesh(X,Y,Z) function is giving an error. Can you post the error?
Below is what I would do to create a simple animation using pcolormesh:
One of the frames:
Does this help? If not, maybe you can clarify the question.
There is another answer presented here that looks simpler thus better (IMHO)
Here is a copy & paste of the alternative solution :
There is an ugly detail you need to take care when using QuadMesh.set_array(). If you intantiate your QuadMesh with X, Y and C you can update the values C by using set_array(). But set_array does not support the same input as the constructor. Reading the source reveals that you need to pass a 1d-array and what is even more puzzling is that depending on the
shading
setting you might need to cut of your arrayC
.Edit: There is even a very old bug report about the confusing array size for
shading='flat'
.That means:
Using QuadMesh.set_array() with shading = 'flat'
'flat' is default value for
shading
.Looks like:
Note that if you omit
C = C[:-1, :-1]
your will get this broken graphic:Using QuadMesh.set_array() with shading = 'gouraud'
If you cut off the last row/column with shade='gouraud' you will get:
The problem was that I was wrongly using
set_array()
routine. It is very important to note that you must pass a 1D array to this routine. To do so, regarding that color, pcolormesh and so on usually plots multidimensional arrays, you should use .ravel() . One more important thing: In order to animate different plots at the same time, theblitz
option atanimate.FuncAnimation
must beFalse
(See section "Animating selected plot elements" of this link).Here I post the code that simple program with various subplots: