matplotlib 动画中的颜色条

colorbar in matplotlib animation

我想给一些数据添加颜色条来制作动画。

但是,我一直在图中创建新的颜色条,但不知道如何删除它们。

一个可重现的例子是:

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

fig = plt.figure(figsize=(7, 7))
ax = fig.add_subplot(111, projection='3d', proj_type='ortho')

X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

data = [X, Y, Z]
    
def myPlot(ax, data):
    surf = ax.plot_surface(*data, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
    
    fig.colorbar(surf, shrink=0.5, aspect=5)
    

def anime(i, ax, data):
    ax.cla()
    data[0] += 0.1
    myPlot(ax, data)
    
animation = FuncAnimation(
                               fig,
                               anime,
                               frames=range(len(X)),
                               fargs=(ax, data)
                           )   

如何在动画中只保留一个颜色条?

亲切的问候

您必须为颜色条创建一个轴:

gs = GridSpec(1, 2, width_ratios = [0.9, 0.05])
fig = plt.figure(figsize = (7, 7))
ax = fig.add_subplot(gs[0], projection = '3d', proj_type = 'ortho')
cbar_ax = fig.add_subplot(gs[1])

并将其作为颜色条定义中的参数传递:

fig.colorbar(surf, shrink = 0.5, aspect = 5, cax = cbar_ax)

完整代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib import cm
from matplotlib.gridspec import GridSpec


gs = GridSpec(1, 2, width_ratios = [0.9, 0.05])
fig = plt.figure(figsize = (7, 7))
ax = fig.add_subplot(gs[0], projection = '3d', proj_type = 'ortho')
cbar_ax = fig.add_subplot(gs[1])


X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

data = [X, Y, Z]


def myPlot(ax, data):
    surf = ax.plot_surface(*data, cmap = cm.coolwarm,
                           linewidth = 0, antialiased = False)

    fig.colorbar(surf, shrink = 0.5, aspect = 5, cax = cbar_ax)


def anime(i, ax, data):
    ax.cla()
    data[0] += 0.1
    myPlot(ax, data)


animation = FuncAnimation(
    fig,
    anime,
    frames = range(len(X)),
    fargs = (ax, data)
)

plt.show()

动画