在 Matplotlib 中動態更新條形圖


要在 Matplotlib 中動態更新條形圖,我們可以採取以下步驟 −

  • 設定圖形大小並調整子圖之間和周圍的填充。
  • 建立一個新圖形或啟用一個現有圖形。
  • 列出資料點和顏色。
  • 使用 bar() 方法用 datacolors 繪製條形圖。
  • 使用 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()

輸出

更新於: 2021 年 7 月 8 日

3K+ 次瀏覽

開啟你的 職業

完成教程獲得認證

開始
廣告
© . All rights reserved.