0

I have been working on a 2 body problem which involves animation of a planet around a star. I want my planet to leave a little trail behind while moving something like this. My code plots everything perfectly except this one thing. I am not able to get the trail of the planet.

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

The output I am getting is just a ball moving around the sun.

1 Answers1

1

I think you were pretty close. The modifications I made were:

  • keep the last trail point to display on the graph (you were only showing the last 2 points)
  • use markevery=[-1] in the plot() call to show the marker only at the end of the line.

full code:

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

Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75