为 maptlotlib FuncAnimation 维护一个颜色条 [英] Maintaining one colorbar for maptlotlib FuncAnimation

查看:20
本文介绍了为 maptlotlib FuncAnimation 维护一个颜色条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个脚本,它使用 matplotlibFuncAnimation 函数为抛物面函数的一系列等高线图制作动画.我想添加一个颜色条,其范围在整个动画中都不会改变.我真的不知道该怎么做.脚本如下所示:

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()

第 42 行是我尝试包含所述颜色条的尝试.这里的问题是,因为 FuncAnimation 多次调用绘图函数(每帧一次),颜色条被多次绘制,从而弄乱了动画.由于 ax 对象似乎是本地的,因此我也想不出任何方法将颜色条实例移动到 animate 函数之外.

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?

请注意,以上是完全有效的代码.它应该适用于适当的 Python 解释器.

Please note the above is fully working code. It should work on the appropriate python interpreter.

推荐答案

我想这个想法是在更新函数之外创建一个等高线图并给它一个颜色条.等高线图需要定义级别,并且需要定义颜色范围.

I guess the idea would be to create a contour plot outside the updating function once and give it a colorbar. The contour plot would then need to have defined levels and the colorrange needs to be defined.

ax.contourf(..., levels=levels, vmin=zmin, vmax=zmax)

其中 zminzmax 是要显示的最小和最大数据,levels 是要使用的级别列表或数组.

where zmin and zmax are the minimum and maximum data to be shown, and levels is the list or array of levels to use.

然后,在动画函数中,您将只使用相同的参数创建一个新的等高线图,而根本不接触颜色条.

Then, inside the animating function, you would only create a new contour plot with those same parameters without touching the colorbar at all.

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()

这篇关于为 maptlotlib FuncAnimation 维护一个颜色条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆