matplotlib 动画中的颜色条

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

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

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

一个可重现的例子是:

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

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

亲切的问候

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

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

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 animate(i, ax, data):
    ax.cla()
    data[0] += 0.1
    myPlot(ax, data)


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

plt.show()

动画

© www.soinside.com 2019 - 2024. All rights reserved.