0

I'm currently coding the trajectories of orbits and am trying to plot two figures during one run. I want one figure to display the orbital path of a satellite with the earth and moon visible on the plot as circles. I then want a separate figure that displays the energies of the trajectory with time.

I think the problem I'm having lies with trying to add circles to the first figure, though I'm at a complete loss on how to circumvent this issue. Re and Rm are just the radius of the earth and moon respectively and the lists are just the lists of my values from the rest of the code. I think the problem is in the fig,axes = plt.subplots line. Instead of getting two separate figures I just get all the values mashed into one figure.

plt.figure(1)
fig, axes = plt.subplots()
earth = plt.Circle((0,0), Re, color = 'blue' )
moon = plt.Circle((0,ym), Rm, color = 'yellow' )
plt.gca().set_aspect('equal', adjustable='box')
plt.plot(xlist,ylist)
axes.add_patch(earth)
axes.add_patch(moon)

plt.figure(2)
plt.plot(tlist,pelist, 'r')
plt.plot(tlist,kelist, 'b')
plt.plot(tlist,elist, 'g')

plt.show()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 2
    A [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) would increase your chances of getting a good answer. It would also be helpful to inclide screenshots of your current output and what you would like to achieve. – DavidG Apr 30 '17 at 23:48

1 Answers1

-1

The second figure does not have a subplot to which plt.plot() could plot. It therefore takes the last open subplot (axes). There is also one figure more than needed in the game.

The easy solution is to delete the double figure creation and add a subplot to the second figure:

import matplotlib.pyplot as plt

fig, axes = plt.subplots()
earth = plt.Circle((0,0),1, color = 'blue' )
moon = plt.Circle((0,2),0.2, color = 'yellow' )
plt.gca().set_aspect('equal', adjustable='box')
axes.add_patch(earth)
axes.add_patch(moon)
plt.plot([0,0],[0,2])

plt.figure(2)
plt.subplot(111)
plt.plot([1,2,3],[3,2,1], 'r')
plt.plot([1,2,3],[2,3,1], 'b')
plt.plot([1,2,3],[1,3,2], 'g')

plt.show()

A better solution which makes it also more comprehensible is to use only the creted objects for plotting (matplotlib API).

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set_aspect('equal', adjustable='box')
earth = plt.Circle((0,0),1, color = 'blue' )
moon = plt.Circle((0,2),0.2, color = 'yellow' )
ax.add_patch(earth)
ax.add_patch(moon)
ax.plot([0,0],[0,2])

fig2, ax2 = plt.subplots()
ax2.plot([1,2,3],[3,2,1], 'r')
ax2.plot([1,2,3],[2,3,1], 'b')
ax2.plot([1,2,3],[1,3,2], 'g')

plt.show()

In this case it's unambiguous to which axes the plots belong.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712