I've made a script which uses matplotlib
's FuncAnimation
function to animate a series of contour plots for paraboloid surface functions. I'd like to add a colorbar for which the range does not change throughout the entire animation. I really have no idea how to do this. The script is shown below:
import numpy as np
import itertools
import matplotlib.pyplot as plt
import matplotlib.mlab as ml
import matplotlib.animation as animation
#Generate some lists
def f(x,y,a):
return a*(x**2+y**2)
avals = list(np.linspace(0,1,10))
xaxis = list(np.linspace(-2,2,9))
yaxis = list(np.linspace(-2,2,9))
xy = list(itertools.product(xaxis,yaxis))
xy = list(map(list,xy))
xy = np.array(xy)
x = xy[:,0]
y = xy[:,1]
x = list(x)
y = list(y)
zlist = []
for a in avals:
z = []
for i, xval in enumerate(x):
z.append(f(x[i],y[i],a))
zlist.append(z)
xi = np.linspace(min(x),max(x),len(x))
yi = np.linspace(min(y), max(y), len(y))
fig,ax = plt.subplots()
def animate(index):
zi = ml.griddata(x, y, zlist[index], xi, yi, interp='linear')
ax.clear()
contourplot = ax.contourf(xi, yi, zi, cmap=plt.cm.hsv,origin='lower')
#cbar = plt.colorbar(contourplot)
ax.set_title('%03d'%(index))
return ax
ani = animation.FuncAnimation(fig,animate,np.array([0,1,2,3,4,5,6,7,8,9]),interval=200,blit=False)
plt.show()
Line 42 was my attempt at including said colorbar. The issue here is that because FuncAnimation
calls the plotting function multiple times (once for each frame), the colorbar gets plotted multiple times thus messing up the animation. I also can't think of any way to move the colorbar instantiation outside of the animate function since the ax
object appears to be local to it.
How can I put one colorbar for the whole animation?
Please note the above is fully working code. It should work on the appropriate python interpreter.