Updating animation variable

巧了我就是萌 提交于 2020-03-23 08:02:09

问题


I am trying to write a program to simulate the orbit of 2 bodies. I have been able to create an animation of the orbits of the 2 bodies and am trying to add a counter at the top corner of the animation to display the kinetic energy of the system.

I have the kinetic energies stored in a list called "ke" and want the animation to display the values in the list corresponding to the positions of the bodies.

However, when I try to write the code needed to display the kinetic energies I have to return the variable "energy_text", but I get an error : AttributeError: 'list' object has no attribute 'set_animated'.

How can I get the variable to be returned/updated correctly?

fig = plt.figure()
ax = plt.axes()
ax = plt.axes(xlim=(-12*10**6, 12*10**6), ylim=(-12*10**6, 12*10**6))
patches = []
patches.append(plt.Circle((r_phobos_h[0][0],r_phobos_h[0][1]),5*10**5,color="b", animated=True))
patches.append(plt.Circle((r_mars_h[0][0],r_mars_h[0][1]),5*10**6,color="orange", animated=True))

energy_text = ax.text(0.02, 0.90, '', transform=ax.transAxes)
def init():
    for i in range(0, len(patches)):
            ax.add_patch(patches[i])
    energy_text.set_text('')
    return patches, energy_text

def animate(i):
    patches[0].center = (r_phobos_h[i][0], r_phobos_h[i][1])
    patches[1].center = (r_mars_h[i][0], r_mars_h[i][1])
    energy_text.set_text(ke[i])
    return patches, energy_text

numframes = len(t)
anim = FuncAnimation(fig, animate, init_func=init, frames = numframes, interval=0.01,blit=True)

plt.show()

回答1:


By writing return patches, energy_text you are not returning a flat list back to the animation. By changing the lines to return patches + [energy_text] it should work:

return patches, energy_text    # -> [[patch_a, patch_b, ...patch_n], text1]
return patches + [energy_text] # -> [patch_a, patch_b, ...patch_n, text1]


来源:https://stackoverflow.com/questions/60545735/updating-animation-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!