如何在 Matplotlib 中對文字新增動畫?
要在 matplotlib 中對文字新增動畫效果,我們可以採取以下步驟 -
- 從 matplotlib 中匯入 "animation" 包。
- 設定圖形大小及調整子圖之間的內邊距。
- 建立新圖形或啟用現有圖形。
- 作為子圖安排的一部分,向圖形新增一個 'ax'。
- 初始化變數 "text" 以儲存字串。
- 在 x=0.20 和 y=0.50 的軸線上新增文字。
- 製作顏色列表。
- 透過重複呼叫 *animate* 函式來製作動畫,其中文字大小會增加並且顏色也會改變。
- 要顯示圖形,請使用 show() 方法。
示例
from matplotlib import animation import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True fig = plt.figure() ax = fig.add_subplot(111) text = 'You are welcome!' txt = ax.text(.20, .5, text, fontsize=15) colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'] def animate(num): txt.set_fontsize(num * 2 + num) txt.set_color(colors[num % len(colors)]) return txt, anim = animation.FuncAnimation(fig, animate, frames=len(text) - 1, blit=True) plt.show()
輸出
將產生以下輸出
廣告