在动画过程中更新 matplotlib 的颜色条



我已经设法让matplotlib使用FuncAnimation更新等高线图,但我无法让颜色栏更新等高线级别。当我替换等高线图时,颜色栏保持不变。如果我用动画的每一帧创建颜色条,那么我会得到一大堆颜色条。

如何更新现有的颜色栏?

下面是一个绘制随时间变化的椭圆函数的例子。值的范围正在稳步减小,所以我需要更新颜色栏。

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

class ContourAnimation(object):
def __init__(self, count):
self.count = count
self.xs = np.arange(count)
self.ys = np.arange(count)
self.x_coords, self.y_coords = np.meshgrid(self.xs, self.ys)
self.z = np.zeros(self.x_coords.shape)
self.contour = None
self.colorbar = None
def update(self, n):
t = (n + 1) / 100
for x in self.xs:
for y in self.ys:
self.z[y][x] = ((x - self.count/2) ** 2 +
((y - self.count/2)/t) ** 2)
if self.contour:
for artist in self.contour.collections:
artist.remove()
self.contour = plt.contourf(self.x_coords, self.y_coords, self.z)
# Without this conditional, I get many colorbars.
if self.colorbar is None:
self.colorbar = plt.colorbar()
return self.contour,

def main():
fig = plt.figure()
fib = ContourAnimation(30)
plt.title('Contour Animation')
fib_ani = animation.FuncAnimation(fig,
fib.update,
interval=500)
plt.show()

if __name__ == '__main__':
main()

仔细看了colorbar()函数后,我发现你可以告诉它把颜色条放在哪个轴上。如果你通过了None的默认值,它会添加一个新的子图并使用它。为了更新颜色栏,我在添加颜色栏子图后记录轴,然后下次重复使用。现在颜色栏更新得很好。

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

class ContourAnimation(object):
def __init__(self, count):
self.count = count
self.xs = np.arange(count)
self.ys = np.arange(count)
self.x_coords, self.y_coords = np.meshgrid(self.xs, self.ys)
self.z = np.zeros(self.x_coords.shape)
self.contour = None
self.colorbar_axes = None
def update(self, n):
t = (n + 1) / 100
for x in self.xs:
for y in self.ys:
self.z[y][x] = ((x - self.count/2) ** 2 +
((y - self.count/2)/t) ** 2)
if self.contour:
for artist in self.contour.collections:
artist.remove()
self.contour = plt.contourf(self.x_coords, self.y_coords, self.z)
self.colorbar = plt.colorbar(cax=self.colorbar_axes)
_, self.colorbar_axes = plt.gcf().get_axes()
return self.contour,

def main():
fig = plt.figure()
fib = ContourAnimation(30)
plt.title('Contour Animation')
fib_ani = animation.FuncAnimation(fig,
fib.update,
interval=500)
plt.show()

if __name__ == '__main__':
main()