-2

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!

4
  • you create both ax1 and ax2 in the first line of code, but then create ax2 again with ax2 = fig.add_subplot(), which is why it overlaps ax1 Commented Feb 24, 2023 at 15:46
  • your code doesnt work r_planet , r , t and E values are missing Commented Feb 26, 2023 at 15:25
  • @pippo1980 I know, I removed extra bits of code to keep the question as simple as possible but perhaps should've clarified the form of these variables Commented Feb 27, 2023 at 11:01
  • @tmdavison thank you! I knew it was something silly. I find the whole subplots thing a bit confusing Commented Feb 27, 2023 at 11:01

1 Answer 1

0

You want to remove the line:

ax2 = fig.add_subplot()
Sign up to request clarification or add additional context in comments.

2 Comments

This is great, but gives two 3D plots, rather than one 2d and one 3d
this initializes the plots as 3d fig, (ax1, ax2) = plt.subplots(2 , subplot_kw={"projection": "3d"}) you can instead do something like fig = plt.figure() -> ax1 = fig.add_subplot(121, projection='3d') and then ax2 = fig.add_subplot(122)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.