This installs numpy, pandas, and matplotlib with it. For interactive 3D plots, polars DataFrames, and saving animations as GIFs, add the optional extras:
That is a 28-day lunar orbit in a handful of lines. Here is what each step does:
create_system() starts an empty system with the standard gravitational constant \(G\).
add_body() places a body with a given mass, position, and velocity. Positions are in meters and velocities in meters per second. The built-in constants (orb.mass_earth, orb.distance_earth_moon, and so on) save you from looking anything up.
simulate() runs the N-body integration forward in time. time_step is the number of seconds per integration step, and duration is the total time to simulate.
plot_orbits() draws a quick 2D trajectory plot with matplotlib.
Each add_* method returns a new system and leaves the original untouched, so the calls chain. The parentheses around the whole expression are only there so that Python lets it span several lines. The semicolon after the plot call keeps a notebook from printing the returned object under the figure. It is not needed in a script.
Customizing the plot
plot_orbits() returns a matplotlib Axes for planar (2D) simulations and an interactive plotly figure for simulations with any motion in z. You can force either one with three_d=True or three_d=False. Because the 2D case returns a regular Axes, you can keep drawing on it, change its title and labels, or pass in your own with ax=.
A common annoyance is that the central body in a two-body system can be invisible. plot_orbits() draws each body as a line along its trajectory, and a much more massive body barely moves, so its line is too small to see. The Sun in a Sun-Earth simulation is the classic example. It is there, but its loop around the barycenter is well inside the Sun itself. The simplest fix is to drop a marker at the origin:
"C0" is the first color in matplotlib’s color cycle, which is the color plot_orbits() gave the Sun, so the marker matches the legend. This works because the Sun sits essentially at the origin throughout the simulation. For systems where the central body moves a noticeable amount, take its position from the simulation DataFrame instead of hardcoding (0, 0).
Watching the orbit in motion
Static plots are useful, but you can also play the simulation forward with animate_system(). With trails=True each body leaves a short wake of recent positions behind it. Pass path= to save the animation as a GIF:
animate_system() is the animated counterpart to plot_system(). It samples the simulation down to roughly fps * duration evenly spaced frames, then draws them with matplotlib and returns a FuncAnimation. Saving a GIF needs the pillow package, which the gif extra installs. Like the static plotters, it switches to a 3D version (animate_system_3d(), an interactive plotly figure with a play button) as soon as any body has motion in z.
Adding more bodies
pyorbiter is a full N-body engine, so you can add as many bodies as you want. Each one gravitationally interacts with every other.
For real solar system bodies, there are two ways to add them.
The manual way. Use add_body() with explicit positions and velocities. This gives you full control and works for any body, real or fictional:
Venus completes more than one full orbit in the time Earth takes to go around once. The inner orbit is both smaller and faster.
The easy way. Use add_sun() and add_planet(), which fill in real masses and orbital elements automatically. Any orbital element can be overridden for “what if” scenarios:
The real orbit of Mars is tilted slightly out of Earth’s orbital plane, so this simulation has motion in z. three_d=False asks for the flat, top-down view anyway.
Under the hood, these use Keplerian orbital elements, a way to describe an orbit by its shape and orientation instead of raw positions and velocities. See Keplerian Orbital Elements for the full explanation.
Removing bodies
You can drop bodies from a system with remove_body(). This is handy when you want to start from load_solar_system() but do not need every body:
If you prefer polars, ask for it with backend="polars", or switch the default once with orb.set_backend("polars"). See pandas or polars.
Saving and sharing systems
You can save a system to disk and restore it later. save_system() writes a small JSON file holding the bodies and the gravitational constant, and load_system() reads it back. A system also has save() and export_bodies() methods that do the same job in a chain:
───────────────────────────────── orbit_system ─────────────────────────────────
G: 6.6743e-11 (standard)
Bodies: 2
id mass x y z vx vy vz
Sun 1.989000e+30 0.000000e+00 0.000000e+00 0.0 0.000000 0.000000 0.0
Earth 5.972000e+24 -3.296559e+10 1.433603e+11 0.0 -29520.187051 -6788.143346 0.0
To share the body table as a CSV, for collaborators or a spreadsheet, use export_bodies():
import pandas as pdsystem.export_bodies(folder /"bodies.csv")pd.read_csv(folder /"bodies.csv")
id
mass
x
y
z
vx
vy
vz
0
Sun
1.989000e+30
0.000000e+00
0.000000e+00
0.0
0.000000
0.000000
0.0
1
Earth
5.972000e+24
-3.296559e+10
1.433603e+11
0.0
-29520.187051
-6788.143346
0.0
save_system() and load_system() preserve the whole system, including \(G\). export_bodies() writes a plain CSV with just the body table, which anyone can open.