#7 — Solar System (2D)



This content originally appeared on DEV Community and was authored by hmza

#7 — Solar System (2D)

In this article, we’ll create a simple 2D simulation of the solar system using Python. We’ll model the Sun and some planets orbiting around it, demonstrating basic orbital mechanics and animation with matplotlib.

🌞 What We’ll Build

  • A 2D plot representing the Sun at the center.
  • Planets orbiting around the Sun in circular orbits.
  • Animation to show continuous orbital movement.

🧮 The Physics Simplified

For simplicity, we’ll use uniform circular motion for planets:

[
x(t) = R \cdot \cos(\omega t + \phi)
]
[
y(t) = R \cdot \sin(\omega t + \phi)
]

Where:

  • ( R ) is the orbit radius
  • ( \omega = \frac{2\pi}{T} ) is angular velocity (T = orbital period)
  • ( \phi ) is the initial phase

💻 Complete Code


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Planet data: name, orbit radius (million km), orbital period (days), color, size
planets = [
    ("Mercury", 58, 88, "gray", 30),
    ("Venus", 108, 225, "orange", 50),
    ("Earth", 150, 365, "blue", 55),
    ("Mars", 228, 687, "red", 40),
    ("Jupiter", 778, 4333, "brown", 90),
    ("Saturn", 1427, 10759, "gold", 80),
]

fig, ax = plt.subplots(figsize=(8,8))
ax.set_facecolor("black")
ax.set_aspect('equal')
ax.set_xlim(-1600, 1600)
ax.set_ylim(-1600, 1600)
ax.axis('off')

# Draw Sun
sun = plt.Circle((0, 0), 100, color='yellow')
ax.add_artist(sun)

# Store planet plots
planet_plots = []
for _, radius, _, color, size in planets:
    p, = ax.plot([], [], 'o', color=color, markersize=size / 10)
    planet_plots.append(p)

# Time variable
t = 0

def update(frame):
    global t
    t += 1
    for i, (_, radius, period, _, _) in enumerate(planets):
        omega = 2 * np.pi / period
        x = radius * np.cos(omega * t)
        y = radius * np.sin(omega * t)
        planet_plots[i].set_data(x, y)
    return planet_plots

ani = animation.FuncAnimation(fig, update, frames=range(0, 365), interval=50, blit=True)
plt.show()

🚀 How It Works

  • We set fixed orbit radii and periods for each planet.
  • The update function moves each planet along its circular orbit by calculating the current position using sine and cosine.
  • matplotlib.animation.FuncAnimation handles the animation.

🤓 Extensions

  • Add elliptical orbits with eccentricity.
  • Add moons orbiting planets.
  • Add planet labels and trails.
  • Use real-time scaled animation speed.

⚠ Disclaimer

This is a simplified 2D model ignoring gravity interactions, planet sizes, and scale differences for visualization purposes only.

Enjoy your orbit! 🌌


This content originally appeared on DEV Community and was authored by hmza