如何在 matplotlib 动画上添加图例?

How to add legend on matplotlib animations?

我有一个用 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)

要更新图例中的标签,您可以使用:

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()

并且输出给出: