How can I make an animation with contourf()?

Dan picture Dan · Apr 14, 2014 · Viewed 10.3k times · Source

I'm trying to animate the wigner function of the spatial coordinates of some time-dependent data. The wigner function is 2 dimensional, so I'm using contourf() to plot it. I have the data stored in a HDF5 file and can make Wigner distributions on the fly, but I can't figure out how to animate it. All of the animation tutorials and examples I've been able to find (for example this one and this one) are strictly for line plots. Specifically, their animate(i) function uses line.set_data(), and I can't seem to find an equivalent for contourf().

How can I animate images made with contourf()?

What's the contourf() equivalent of set_data()?

Answer

iury simoes-sousa picture iury simoes-sousa · Jul 15, 2016

There's a simple way to do it with FuncAnimation: You must have a function that clears the axis and plot a new contour based on frame number. Don't forget to set blit as False.

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

DATA = np.random.randn(800).reshape(10,10,8)


fig,ax = plt.subplots()

def animate(i):
       ax.clear()
       ax.contourf(DATA[:,:,i])
       ax.set_title('%03d'%(i)) 

interval = 2#in seconds     
ani = animation.FuncAnimation(fig,animate,5,interval=interval*1e+3,blit=False)

plt.show()