Jonathan Lalieu
Jonathan Lalieu

Reputation: 13

Animating a pcolormesh with contours with maltpoltlib

I am working on something : I need to vizualize the progress of, let us say heat, in time and on a surface.

I'm having some troubles animating a pcolormesh with contours : the contour is indeed animated, but the pcolormesh is not ; I only get the first one that is never replaced.

My code is quite like this :

#x, y and z_temp are previously extracted from an Excel file
z=np.zeros(time,y,x)
for t in range(time):
    for m in range(len(y)):
        for n in range(len(x)):
            z[t][m][n] = z_temp[t]
x,y=np.meshgrid(x,y)

im = ax.contour(x, y, z[0], 20)
fond = ax.pcolormesh(x, y, z[0], cmap=cm.get_cmap('afmhot_r'))

def animate(t):
    print(t)
    ax.cla()
    fond = ax.pcolormesh(x, y, z[t], cmap=cm.get_cmap('afmhot_r'))
    im = ax.contour(x, y, z[t], 20, cmap=cm.get_cmap('cool'))
    return im, fond,

ani = anima.FuncAnimation(fig, animate, frames=time, interval=400, repeat_delay=1000)
plt.show()

I tried to get inspired by this post : Animation with pcolormesh routine in matplotlib, how do I initialize the data? as well as others that dealt with animation this time, but I seem incapable of combining the solutions I found. Following the solution of the link, I ended up having nothing at all...

Could anyone help ?

EDIT :

Maybe I should be more specific about my other attempt. I replaced the "def animate(t)" section by something that got me only the contour, but still animated :

def init():
    fond.set_array(np.array([]))
    return im, fond,
def animate(t):
    print(t) 
    ax.cla()  
    fond.set_array(z[t])  
    im = ax.contour(x, y, z[t], 20, cmap=cm.get_cmap('cool'))  
    return im, fond,

Upvotes: 1

Views: 1070

Answers (1)

Bart
Bart

Reputation: 10308

Beyond some coding errors, I don't see why this functionally wouldn't work. This minimal example updates both the pcolormesh and contour's without a problem. Could you test this to see if it works for you?

import numpy as np
import matplotlib.pylab as plt
import matplotlib.animation as animation

time = 10
x = np.linspace(0,5,6)
y = np.linspace(0,6,7)
z = np.random.random((time, y.size, x.size))

fig  = plt.figure()
ax   = plt.subplot(111)
im   = ax.contour(x, y, z[0], 20)
fond = ax.pcolormesh(x, y, z[0], cmap=plt.cm.get_cmap('afmhot_r'))

def animate(t):
    print(t)
    ax.cla()
    fond = ax.pcolormesh(x, y, z[t], cmap=plt.cm.get_cmap('afmhot_r'))
    im   = ax.contour(x, y, z[t], 20, cmap=plt.cm.get_cmap('cool'))
    return im, fond,

ani = animation.FuncAnimation(fig, animate, frames=time, interval=400, repeat_delay=1000)
plt.show()

Upvotes: 1

Related Questions