在 Matplotlib 繪圖上繪製動畫文字


要為繪圖中的文字新增動畫效果,我們可以執行以下步驟:

  • 設定圖片大小和調整子圖之間的邊距。
  • 設定 x 及 y 軸的限制條件。
  • 初始化一個變數,字串
  • 使用 text() 函式在繪圖上放置文字。
  • 使用 FuncAnimation() 函式為文字新增動畫。將文字設定在文字軸。
  • 關閉軸。
  • 要顯示圖片,請使用 show() 函式。

示例

from matplotlib import pyplot as plt, animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
ax.set(xlim=(-1, 1), ylim=(-1, 1))
string = 'Hello, how are you doing?'
label = ax.text(0, 0, string[0], ha='center', va='center', fontsize=20, color="Red")

def animate(i):
   label.set_text(string[:i + 1])

anim = animation.FuncAnimation(
   fig, animate, interval=200, frames=len(string))
ax.axis('off')
plt.show()

輸出

更新時間:2021-06-16

2K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告