我正在嘗試動態更新影片matplotlib圖表中的條形圖值標簽。我正在使用的玩具代碼在這里:
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
fig = plt.figure()
x = [1,2,3,4,5]
y = [5,7,2,5,3]
ax1 = plt.subplot(2, 1, 1)
ax2 = plt.subplot(2, 1, 2)
data = np.column_stack([np.linspace(0, yi, 50) for yi in y])
rects = ax1.bar(x, data[0], color='c')
line, = ax2.plot(x, data[0], color='r')
ax1.set_ylim(0, max(y))
ax1.bar_label(rects, padding=1)
ax2.set_ylim(0, max(y))
def animate(i):
for rect, yi in zip(rects, data[i]):
rect.set_height(yi)
ax1.bar_label(rects, padding=1)
line.set_data(x, data[i])
anim = animation.FuncAnimation(fig, animate, frames=len(data), interval=40)
plt.show()
在每個時間步都列印值標簽,但它們保留在繪圖上。

如何在不讓舊標簽保留在圖表上的情況下更新影片中每一步的值標簽?
uj5u.com熱心網友回復:
您可以rects在清除中的每個幀中重新創建ax1:
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
fig = plt.figure()
x = [1,2,3,4,5]
y = [5,7,2,5,3]
ax1 = plt.subplot(2, 1, 1)
ax2 = plt.subplot(2, 1, 2)
data = np.column_stack([np.linspace(0, yi, 50) for yi in y])
ax1.set_ylim(0, max(y))
ax2.set_ylim(0, max(y))
line, = ax2.plot(x, [0] * len(x), color='r')
def animate(i):
ax1.cla()
ax1.set_ylim(0, max(y))
rects = ax1.bar(x, data[i], color='c')
ax1.bar_label(rects, padding=1)
line.set_data(x, data[i])
anim = animation.FuncAnimation(fig, animate, frames=len(data), interval=40)
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/362626.html
標籤:Python matplotlib
