如何使用動畫更新 Matplotlib 中的繪圖示題?


要使用動畫更新 Matplotlib 中的繪圖示題,我們可以採取以下步驟 −

  • 設定圖形尺寸並調整子圖之間和周圍的填充。
  • 使用 figure() 方法建立新圖形或啟用現有圖形。
  • 使用 numpy 建立 x y 資料點。
  • 獲取當前座標軸。
  • 使用 text() 方法向座標軸新增文字。
  • 新增可用於透過重複呼叫函式建立動畫的 animate 方法。
  • 要顯示圖形,請使用 show() 方法。

示例程式碼

import numpy as np
from matplotlib import pyplot as plt, animation

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()

x = np.linspace(-10, 10, 1000)
y = np.sin(x)

plt.plot(x, y)

ax = plt.gca()
ax.text(0.5, 1.100, "y=sin(x)", bbox={'facecolor': 'red',
                                       'alpha': 0.5, 'pad': 5},
         transform=ax.transAxes, ha="center")

def animate(frame):
   ax.text(0.5, 1.100, "y=sin(x), frame: %d" % frame,
            bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 5},
            transform=ax.transAxes, ha="center")

ani = animation.FuncAnimation(fig, animate, interval=100,
                              frames=10, repeat=True)

plt.show()

輸出

更新於: 09-06-2021

已逾 2 萬人次瀏覽

啟動您的職業

完成課程認證

開始
廣告
© . All rights reserved.