我有一個用 python 撰寫的軌道影片。我想要一個標簽是時間“dt”的傳說。這次沿軌道更新(增加)。例如,在 gif 的第一幀中,圖例應該是“dt”,在第二幀中,應該是 dt dt,依此類推。我嘗試了一些不起作用的東西。也許我沒有使用正確的命令。出現的錯誤:TypeError: __init__() got multiple values for argument 'frames' 。有人知道怎么做這個傳說嗎?代碼在上面。
fig = plt.figure()
plt.xlabel("x (km)")
plt.ylabel("y (km)")
plt.gca().set_aspect('equal')
ax = plt.axes()
ax.set_facecolor("black")
circle = Circle((0, 0), rs_sun, color='dimgrey')
plt.gca().add_patch(circle)
plt.axis([-(rs_sun / 2.0) / u1 , (rs_sun / 2.0) / u1 , -(rs_sun / 2.0) / u1 , (rs_sun / 2.0) / u1 ])
# Legend
dt = 0.01
leg = [ax.plot(loc = 2, prop={'size':6})]
def update(dt):
for i in range(len(x)):
lab = 'Time:' str(dt dt*i)
leg[i].set_text(lab)
return leg
# GIF
graph, = plt.plot([], [], color="gold", markersize=3)
plt.close()
def animate(i):
graph.set_data(x[:i], y[:i])
return graph,
skipframes = int(len(x)/500)
if skipframes == 0:
skipframes = 1
ani = FuncAnimation(fig, update, animate, frames=range(0,len(x),skipframes), interval=20)
uj5u.com熱心網友回復:
要更新圖例中的標簽,您可以使用:
graph, = plt.plot([], [], color="gold",lw=5,markersize=3,label='Time: 0')
L=plt.legend(loc=1)
L.get_texts()[0].set_text(lab)
L.get_texts()[0].set_text(lab) 應該在更新函式內部呼叫以在影片的每次迭代中重繪 標簽。
您可以在下面找到一個最小示例來說明該程序:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig,ax = plt.subplots()
dt = 0.01
N_frames=30
x=np.random.choice(100,size=N_frames,) #Create random trajectory
y=np.random.choice(100,size=N_frames,) #Create random trajectory
graph, = plt.plot([], [], color="gold",lw=5,markersize=3,label='Time: 0')
L=plt.legend(loc=1) #Define legend objects
def init():
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
return graph,
def animate(i):
lab = 'Time:' str(round(dt dt*i,2))
graph.set_data(x[:i], y[:i])
L.get_texts()[0].set_text(lab) #Update label each at frame
return graph,
ani = animation.FuncAnimation(fig,animate,frames=np.arange(N_frames),init_func=init,interval=200)
plt.show()
輸出給出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/420534.html
標籤:
下一篇:運行冒泡排序時出現分段錯誤
