I have two sets of x,y coordinates that describe the motions of two planets orbiting the sun over time. My assignment asks me to animate this data in Python using Matplotlib, but my syllabus doesn't cover it well. I've managed to animate the trajectory with the help of MatPlotLib's documentation, but I am unable to display a moving dot at the current locations of the planets:
import matplotlib.pylab as plt
import matplotlib.animation as animation
earthx = planetRs[0][0] #these are arrays of x and y coordinates of Earth and Mars
earthy = planetRs[0][1]
marsx = planetRs[2][0]
marsy = planetRs[2][1]
fig, ax = plt.subplots()
line1 = ax.plot(marsx[0], marsy[0], label='Mars')[0]
line2 = ax.plot(earthx[0], earthy[0], label='Earth')[0]
ax.set(xlim=[-2, 2], ylim=[-2, 2], xlabel='X position', ylabel='Y position')
ax.legend()
def update(frame):
line1.set_xdata(marsx[:frame])
line1.set_ydata(marsy[:frame])
line2.set_xdata(earthx[:frame])
line2.set_ydata(earthy[:frame])
return line1, line2
ani = animation.FuncAnimation(fig=fig, func=update, frames=60, interval=30)
plt.close()
ani
Every time I try, it becomes a line with dots at each x,y coordinate. I want the dots to merely show the most recent x,y location of both planets. Could someone help me out?
You can plot single points for Earth and Mars, and then update each point's position to the current frame coordinates.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
earthx = planetRs[0][0] #these are arrays of x and y coordinates of Earth and Mars
earthy = planetRs[0][1]
marsx = planetRs[2][0]
marsy = planetRs[2][1]
fig, ax = plt.subplots()
line1 = ax.plot([], [], 'ro', label='Mars')[0]
line2 = ax.plot([], [], 'bo', label='Earth')[0]
ax.set(xlim=[-2, 2], ylim=[-2, 2], xlabel='X position', ylabel='Y position')
ax.legend()
ax.grid(False)
def init():
line1.set_data([], [])
line2.set_data([], [])
return line1, line2
def update(frame):
line1.set_data(marsx[frame], marsy[frame])
line2.set_data(earthx[frame], earthy[frame])
return line1, line2
ani = animation.FuncAnimation(
fig=fig, func=update, init_func=init,
frames=len(earthx), interval=30, blit=True)
plt.close()
ani