我已经编写了一个脚本,该脚本使用matplotlib的FuncAnimation函数为抛物面表面函数设置了一系列等高线图。我想添加一个颜色条,其颜色范围在整个动画中不会改变。我真的不知道该怎么做。该脚本如下所示:
matplotlib
FuncAnimation
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()
第42行是我尝试包含所述色标的尝试。这里的问题是,因为FuncAnimation多次调用绘图函数(每帧一次),所以彩条被多次绘制,从而使动画混乱。我也想不出任何方法将颜色条实例化移动到动画功能之外,因为该ax对象似乎是本地的。
ax
如何为整个动画放置一个颜色条?
请注意,以上代码是完全有效的代码。它应该在适当的python解释器上工作。
我想这个想法是在更新功能之外创建一个轮廓图,并给它一个颜色条。然后,轮廓图将需要具有定义的级别,并且需要定义颜色范围。
ax.contourf(..., levels=levels, vmin=zmin, vmax=zmax)
其中zmin和zmax是要显示的最小和最大数据,levels是要使用的级别的列表或数组。
zmin
zmax
levels
然后,在动画功能内部,您将只使用相同的参数创建一个新的轮廓图,而完全不触摸颜色栏。
import numpy as np import itertools import matplotlib.pyplot as plt import matplotlib.mlab as ml import matplotlib.animation as animation 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 = np.array(list(map(list,xy))) x = xy[:,0] y = xy[:,1] 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)) zmin = min([min(zl) for zl in zlist]) zmax = max([max(zl) for zl in zlist]) levels = np.linspace(zmin, zmax,41) kw = dict(levels=levels, cmap=plt.cm.hsv, vmin=zmin, vmax=zmax, origin='lower') fig,ax = plt.subplots() zi = ml.griddata(x, y, zlist[0], xi, yi, interp='linear') contourplot = ax.contourf(xi, yi, zi, **kw) cbar = plt.colorbar(contourplot) def animate(index): zi = ml.griddata(x, y, zlist[index], xi, yi, interp='linear') ax.clear() ax.contourf(xi, yi, zi, **kw) ax.set_title('%03d'%(index)) ani = animation.FuncAnimation(fig,animate,10,interval=200,blit=False) plt.show()