如何只保留一个颜色条用于动画

问题描述 投票:0回答:1

我正在尝试使用 Python 中的 Matplotlib 动画包创建动画。但是,我遇到了动画中出现多个颜色条的问题。这可能是因为每个后续帧中的颜色条不会覆盖前一帧。如果能够提供解决方案,我将不胜感激。您可以在下面找到我正在使用的代码和 GIF。

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.animation import PillowWriter
import numpy as np


fig, ax = plt.subplots()

def animate(i):
    ax.clear()
    np.random.seed(i)
    z = np.random.rand(20, 20)
    im = ax.imshow(z, origin='lower')

    cbar = fig.colorbar(im, ax=ax, orientation='vertical')


ani = FuncAnimation(fig, animate, frames=20, interval=5, repeat=False)

plt.tight_layout()
plt.show()

enter image description here

python matplotlib colorbar matplotlib-animation
1个回答
0
投票

在动画开始之前,在第 0 帧,您必须初始化一个初始 z 数组。

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.animation import PillowWriter
import numpy as np


fig, ax = plt.subplots()

z = np.random.rand(20, 20)
im = ax.imshow(z, origin='lower')

cbar = fig.colorbar(im, ax=ax, orientation='vertical')

def animate(i):
    global z, im, cbar

    ax.clear()
    cbar.remove()
    
    np.random.seed(i)
    z = np.random.rand(20, 20)
    im = ax.imshow(z, origin='lower')

    cbar = fig.colorbar(im, ax=ax, orientation='vertical')


ani = FuncAnimation(fig, animate, frames=20, interval=5, repeat=False)

plt.tight_layout()
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.