我想在星球动画中找到线索

2024-06-11 22:53:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在研究一个双体问题,涉及到一颗行星围绕一颗恒星的动画。我想让我的星球在移动类似this的东西时留下一点痕迹。我的代码完美地描绘了一切,除了这一点。我找不到行星的踪迹

fig, ax = plt.subplots()

print(func(0.98, -np.pi, 0, 0, 0.001))
ax.set(xlim = (-1.2,1.5), ylim = (-1.5,1.5), xlabel = 'x axis', ylabel='y axis', title = 'Planet\'s orbit')

def polar_animator(i):
    trail = 40
    l1.set_data(x_graph[i-1:i], y_graph[i-1:i])
    return l1,

l1, = ax.plot([],[], 'o-')
l2, = ax.plot([-0.8],[0],marker= 'o')

    
ani = animation.FuncAnimation(fig, polar_animator, frames= len(x_graph), interval=5, blit=True)
ani.save('planet.mp4', writer= 'ffmpeg')

我得到的输出只是一个绕太阳运动的球


Tags: l1plotfig动画行星axthisgraph
1条回答
网友
1楼 · 发布于 2024-06-11 22:53:45

我觉得你很接近。我所作的修改是:

  • 保留要在图形上显示的最后一个trail点(您只显示了最后两个点)
  • plot()调用中使用markevery=[-1]仅在行尾显示标记

完整代码:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

x_graph = np.linspace(0, 1, 100)
y_graph = x_graph
trail = 40

fig, ax = plt.subplots()
ax.set(xlim=(-1.2, 1.5), ylim=(-1.5, 1.5), xlabel='x axis', ylabel='y axis', title='Planet\'s orbit')


def polar_animator(i, trail=40):
    l1.set_data(x_graph[i - trail:i], y_graph[i - trail:i])
    return l1,


l1, = ax.plot([], [], 'o-', markevery=[-1])
l2, = ax.plot([-0.8], [0], marker='o')

ani = animation.FuncAnimation(fig, polar_animator, frames=len(x_graph), fargs=(trail,), interval=5, blit=True)

enter image description here

相关问题 更多 >