pythonpython-3.xmatplotlibplotorbital-mechanics

How can have multiple plots output from python, one 2D, one 3D


I want to make a plot of an orbit and it's energy with respect to time. I want to have the program output a 3D figure of the orbit, and a 2D figure of the total energy against time. I have been trying to use matplotlib and get my head around subplots and such but with varying levels of success.

This is my most recent bit of code

import matplotlib.pyplot as plt

import numpy as np

# Create 3D plot of the satellite's orbit
fig, (ax1, ax2) = plt.subplots(2 , subplot_kw={"projection": "3d"})

# Create a sphere to represent the planet
u, v = np.mgrid[0:2*np.pi:100j, 0:np.pi:100j]
x = r_planet * np.cos(u) * np.sin(v)
y = r_planet * np.sin(u) * np.sin(v)
z = r_planet * np.cos(v)
ax1.plot_surface(x, y, z, cmap = 'gray', alpha=0.5)

# Plot Orbit
ax1.plot(r[:, 0], r[:, 1], r[:, 2])
ax1.set_xlabel('X (m)')
ax1.set_ylabel('Y (m)')
ax1.set_zlabel('Z (m)')
ax1.set_title('Satellite orbiting planet')

# Plot Energy
ax2 = fig.add_subplot()
ax2.plot(t, E)
ax2.set_xlabel('Time (s)')
ax2.set_ylabel('Total Energy (J)')
ax2.set_title('Total Energy of Satellite')

plt.show()

This is the present output

I have tried messing around with subplots and other stuff but the result always seems to be that they end up plotting on top of one another. Any help would be much appreciated.

Also you'll have to ignore my orbits violation of conservation of energy, I'm working on this! Part of having the graph is to keep testing this.

Thank you!


Solution

  • You want to remove the line:

    ax2 = fig.add_subplot()