如何在 Matplotlib 中設定顏色條的動畫?


要在 matplotlib 中設定顏色條的動畫,我們可以採用以下步驟:

  • 設定圖片大小並調整子圖之間和周圍的邊距。

  • 建立新的圖片或啟用現有的圖片。

  • '~.axes.Axes' 新增到圖片作為子圖的一部分。

  • 根據預先存在的座標軸(即 ax 物件)例項化 Divider 並返回指定單元格的新座標軸定位器。

  • 在指定 *position* 處建立座標軸,其 height(或 width)與主座標軸相同。

  • 使用 numpy 建立隨機資料。

  • 使用 imshow() 方法繪製隨機資料。

  • 設定圖片標題。

  • 對顏色對映表進行初始化。

  • 要設定顏色條的動畫,請使用 animate() 方法。

  • 要顯示圖片,請使用 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()

輸出

更新於: 2021 年 6 月 16 日

2K+ 瀏覽量

開啟你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.