在 Matplotlib 中動態更新條形圖
要在 Matplotlib 中動態更新條形圖,我們可以採取以下步驟 −
- 設定圖形大小並調整子圖之間和周圍的填充。
- 建立一個新圖形或啟用一個現有圖形。
- 列出資料點和顏色。
- 使用 bar() 方法用 data 和 colors 繪製條形圖。
- 使用 FuncAnimation() 類,透過重複呼叫設定條形高度和條形面顏色的函式 animation,製作一個動畫。
- 使用 show() 方法顯示圖形。
示例
import numpy as np from matplotlib import animation as animation, pyplot as plt, cm plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig = plt.figure() data = [1, 4, 3, 2, 6, 7, 3] colors = ['red', 'yellow', 'blue', 'green', 'black'] bars = plt.bar(data, data, facecolor='green', alpha=0.75) def animate(frame): global bars index = np.random.randint(1, 7) bars[frame].set_height(index) bars[frame].set_facecolor(colors[np.random.randint(0, len(colors))]) ani = animation.FuncAnimation(fig, animate, frames=len(data)) plt.show()
輸出

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP