如何在Matplotlib中对colorbar进行动画处理?
要在matplotlib中对colorbar进行动画处理,可以按照以下步骤进行操作−
- 设置图形大小并调整子图之间和周围的填充。
-
创建新图或激活现有图。
-
将 ‘~.axes.Axes’ 作为子图排列的一部分添加到图中。
-
基于现有的轴即ax对象来实例化 Divider 并返回一个指定单元格的新轴定位器。
-
使用与主轴相同的高度(或宽度)在给定的 position 处创建轴。
-
使用numpy创建随机数据。
-
使用 imshow() 方法绘制随机数据。
-
设置绘图的标题。
-
实例化颜色映射列表。
-
使用 animate() 方法动画处理colorbar。
-
使用 show() 方法显示图形。
示例
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.axes_grid1 import make_axes_locatable
plt.rcParams[“figure.figsize”] = [7.50, 3.50]
plt.rcParams[“figure.autolayout”] = True
fig = plt.figure()
ax = fig.add_subplot(111)
div = make_axes_locatable(ax)
cax = div.append_axes('right', '5%', '5%')
data = np.random.rand(5, 5)
im = ax.imshow(data)
cb = fig.colorbar(im, cax=cax)
tx = ax.set_title('Frame 0')
cmap = ["copper", 'RdBu_r', 'Oranges', 'cividis', 'hot', 'plasma']
def animate(i):
cax.cla()
data = np.random.rand(5, 5)
im = ax.imshow(data, cmap=cmap[i%len(cmap)])
fig.colorbar(im, cax=cax)
tx.set_text('Frame {0}'.format(i))
ani = animation.FuncAnimation(fig, animate, frames=10)
plt.show()