用 matplotlib 儲存散點圖動畫
若要使用 matplotlib 儲存散點圖動畫,可按以下步驟操作 −
- 設定圖形大小,調整子圖之間和子圖周圍的填充。
- 初始化四個變數步驟、節點、位置和解。
- 在列表中追加位置和解的值。
- 建立一個圖形和一組子圖。
- 為標記大小初始化一個變數。
- 配置網格線。
- 透過重複呼叫函式 *animate* 建立動畫,以清除軸、新增新的軸子圖並在軸上繪製散點。
- 將動畫散點圖另存為 .gif 檔案。
示例
import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True steps = 50 nodes = 100 positions = [] solutions = [] for i in range(steps): positions.append(np.random.rand(2, nodes)) solutions.append(np.random.random(nodes)) fig, ax = plt.subplots() marker_size = 50 def animate(i): fig.clear() ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(0, 1), ylim=(0, 1)) ax.set_xlim(0, 1) ax.set_ylim(0, 1) s = ax.scatter(positions[i][0], positions[i][1], s=marker_size, c=solutions[i], cmap="RdBu_r", marker="o", edgecolor='black') plt.grid(b=None) ani = animation.FuncAnimation(fig, animate, interval=100, frames=range(steps)) ani.save('animation.gif', writer='pillow')
輸出
廣告