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

时间:2018-11-17 01:33:38

标签: python animation matplotlib

我设法使用FuncAnimation使matplotlib更新轮廓图,但是我无法获得颜色条来更新轮廓线。当我替换等高线图时,颜色条不变。如果我在动画的每一帧都创建一个颜色条,那么我会得到一堆颜色条。

如何更新现有的颜色栏?

这是一个绘制随时间变化的椭圆函数的示例。值的范围在逐渐减小,因此我需要更新颜色栏。

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

1 个答案:

答案 0 :(得分:0)

仔细观察colorbar() function后,我发现您可以告诉它将色标放入哪个轴。如果传递默认值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()