import matplotlib.pyplot as plt
import numpy as np
planets = [
(1, 0.0167, 'gray'),
(1.5, 0.0934, 'red'),
(0.72, 0.0067, 'orange'),
(0.39, 0.206, 'blue'),
(5.2, 0.0489, 'brown'),
]
theta = np.linspace(0, 2 * np.pi, 500)
fig, ax = plt.subplots(figsize=(6, 6))
ax.set_aspect('equal')
ax.set_title('Planetary Orbit Map', fontsize=16)
ax.set_facecolor("black")
for a, e, color in planets:
b = a * np.sqrt(1 - e**2)
x = a * np.cos(theta) - a * e
y = b * np.sin(theta)
ax.plot(x, y, color=color, linewidth=2, label=f'a={a}, e={e:.3f}')
ax.plot(0, 0, 'o', color='yellow', markersize=12, label='Sun')
ax.set_xlim(-6, 6)
ax.set_ylim(-6, 6)
ax.legend(loc='upper right', fontsize=8)
ax.axis('off')
plt.show()
#source code --> clcoding.com
Code Explanation:
1. Import Libraries
import matplotlib.pyplot as plt
import numpy as np
matplotlib.pyplot: For plotting.
numpy: For numerical operations (e.g., trigonometric functions and arrays).
2. Define Planet Parameters
planets = [
(1, 0.0167, 'gray'), # Earth
(1.5, 0.0934, 'red'), # Mars
(0.72, 0.0067, 'orange'), # Venus
(0.39, 0.206, 'blue'), # Mercury
(5.2, 0.0489, 'brown'), # Jupiter
]
Each tuple represents a planet:
a: Semi-major axis (how far the planet is from the Sun on average).
e: Eccentricity (how stretched the orbit is; 0 = circle, close to 1 = elongated).
color: For visualization.
3. Generate Angular Values
theta = np.linspace(0, 2 * np.pi, 500)
Creates 500 points from 0 to 2π radians to represent the angle around a circle (full orbit).
4. Create Plot
fig, ax = plt.subplots(figsize=(8, 8))
ax.set_aspect('equal')
ax.set_title('Planetary Orbit Map', fontsize=16)
ax.set_facecolor("black")
Initializes a square figure and axes.
set_aspect('equal'): Ensures x and y scales are the same, preserving orbit shape.
Background color is set to black for space-like look.
5. Plot Orbits
for a, e, color in planets:
b = a * np.sqrt(1 - e**2) # semi-minor axis from semi-major and eccentricity
x = a * np.cos(theta) - a * e # orbit in x, offset for Sun at focus
y = b * np.sin(theta) # orbit in y
ax.plot(x, y, color=color, linewidth=2, label=f'a={a}, e={e:.3f}')
This loop:
Calculates the elliptical shape for each planet.
x and y define the shape of the orbit using parametric equations.
-a * e recenters the ellipse so the Sun sits at one focus (per Kepler's First Law).
Draws the orbit with the specified color.
6. Draw the Sun
ax.plot(0, 0, 'o', color='yellow', markersize=12, label='Sun')
Puts the Sun at the origin (0,0) in bright yellow.
7. Customize Axes
ax.set_xlim(-6, 6)
ax.set_ylim(-6, 6)
ax.legend(loc='upper right', fontsize=8)
ax.axis('off')
Sets limits to frame the orbits.
Adds a legend with orbit info.
Hides axis lines/ticks for clean appearance.
8. Display Plot
plt.show()
Displays the final orbit map.


0 Comments:
Post a Comment