Solar System Simulation in Python
Introduction
In this blog post, we'll walk through creating a Solar System simulation using Python and Matplotlib. This project is perfect for beginners looking to explore the basics of orbital mechanics and animations in Python.
Features of the Solar System Simulation
- Simulates the orbits of planets around the Sun using basic trigonometry.
- Includes eight planets: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune.
- Uses Matplotlib to visualize the planets' motion in a 2D space.
- Customizable orbital radii and periods for each planet.
The Python Code
Below is the Python code for the Solar System simulation. You can easily copy it and try it out in your Python environment.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
# Planetary data: (name, color, orbital radius in AU, orbital period in Earth years)
planets = [
("Mercury", "gray", 0.39, 0.24),
("Venus", "yellow", 0.72, 0.61),
("Earth", "blue", 1.00, 1.00),
("Mars", "red", 1.52, 1.88),
("Jupiter", "orange", 5.20, 11.86),
("Saturn", "gold", 9.58, 29.46),
("Uranus", "lightblue", 19.22, 84.01),
("Neptune", "darkblue", 30.05, 164.8)
]
# Initialize figure and axes
fig, ax = plt.subplots(figsize=(10, 10))
ax.set_xlim(-35, 35)
ax.set_ylim(-35, 35)
ax.set_aspect('equal')
ax.set_title('Solar System Simulation')
ax.set_xlabel('AU')
ax.set_ylabel('AU')
# Create scatter plot for the Sun
sun = plt.Circle((0, 0), 0.1, color='yellow', zorder=10)
ax.add_artist(sun)
# Create plot elements for planets
planet_plot = []
for name, color, radius, period in planets:
plot, = ax.plot([], [], 'o', color=color, label=name)
planet_plot.append((plot, radius, period))
# Initialize function for animation
def init():
for plot, _, _ in planet_plot:
plot.set_data([], []) # Initialize with empty sequences
return [plot for plot, _, _ in planet_plot]
# Update function for animation
def update(frame):
for plot, radius, period in planet_plot:
theta = 2 * np.pi * (frame / (period * 365)) # Angle of the planet
x = radius * np.cos(theta)
y = radius * np.sin(theta)
plot.set_data([x], [y]) # Ensure x and y are sequences
return [plot for plot, _, _ in planet_plot]
# Create animation
ani = FuncAnimation(fig, update, frames=range(365), init_func=init, blit=True, interval=50)
# Add legend
ax.legend(loc='upper right')
# Show the plot
plt.show()
Conclusion
This simple Solar System simulation is a great way to start learning about Python animations and visualizations. Feel free to modify the code to add more features or customize the planetary parameters. Happy coding!