Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 57 ยท Projects

Project: Physics and Math Visualizer

Visualize physics and math with Matplotlib: projectile paths, a pendulum phase portrait, Lissajous curves, the Mandelbrot set, a streamplot and a filmstrip.

Physics and mathematics are full of pictures: arcs of thrown balls, spirals in phase space, fractal boundaries, fields of invisible forces. Matplotlib is the tool scientists reach for when they want to see these things, and NumPy does the number crunching. In this project you will build a small "visualizer" with six exhibits, each one using a different part of the library.

You will simulate projectiles with and without air drag, trace a pendulum's phase portrait with a Runge-Kutta integrator, draw Lissajous curves, render the Mandelbrot set with imshow, show an electric field with streamplot, and finish with a filmstrip: a row of snapshots that stands in for an animation. Animation itself is covered in Animation Concepts; a filmstrip gives you the same insight on a static page. You should be comfortable with Line Plots in Depth, Multiple Subplots and Heatmaps and Images.

Six exhibits

Projectiles Vacuum against air drag.
Pendulum A phase portrait of swings and spins.
Lissajous Two waves, one curve.
Mandelbrot A fractal rendered as an image.

Then a vector field and a filmstrip.

1 / 2

Exhibit 1: projectiles, with and without air

In a vacuum, a ball launched at speed v0 and angle a follows x = v0 cos(a) t and y = v0 sin(a) t - g t^2 / 2, so you can compute the whole path with one NumPy expression. Real balls feel drag, which has no neat formula, so we step through time instead: update the velocity from the forces, then the position from the velocity, a tiny dt at a time. This is the Euler method, the simplest numerical integrator. The drag force here grows with the square of the speed and points against the velocity.

We launch five angles with the same speed and color them by angle with a sequential colormap. Both panels use set_aspect("equal"), so a 45 degree launch really looks like 45 degrees and the arcs are not stretched.

Python Projectile paths: vacuum against drag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The left panel is symmetric: 15 and 75 degrees land at the same spot, as do 30 and 60, and 45 degrees goes farthest. On the right, drag shortens every flight, hurts the high, slow-moving arcs the most, and breaks the symmetry. The best angle drops below 45, to about 40 degrees in our run. A one-line change to a simulation uncovered a result you cannot get from the textbook formula.

Exhibit 2: the pendulum's phase portrait

A pendulum's state is two numbers: its angle theta and its angular velocity omega. Its motion follows theta'' = -(g / L) sin(theta). A phase portrait plots omega against theta, ignoring time, and shows every possible kind of motion in one picture.

Euler's method drifts when you simulate oscillations, so here we use fourth-order Runge-Kutta (RK4), which samples the slope four times per step and combines them. It is only a few lines, and its energy error stays around one part in a hundred million over our run, which you will see printed.

flowchart LR
    A["state<br/>(theta, omega)"] --> B["derivative<br/>(omega, -g/L sin theta)"]
    B --> C["RK4 step<br/>dt = 0.01"]
    C --> D["store state<br/>in an array"]
    D --> A

A simulation is a loop: derive, step, store. The stored array is what Matplotlib draws.

Small swings trace closed ovals around the origin. Bigger swings produce distorted loops. A launch with enough energy swings all the way over the top and keeps rotating, which shows up as a wavy line running across the plot. We wrap the angle into the range -pi to pi and put nan where the line wraps around, so Matplotlib breaks the line instead of drawing a stripe across the picture.

Python Phase portrait of a pendulum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The ovals near the center are almost circular for small energy and stretch as the swing grows. The curve that starts at 3.1 radians, just short of straight up, hugs the boundary between the two worlds: that boundary is the separatrix, where the pendulum has just enough energy to reach the top. Above it, the starts with omega0 of 7.0 and 8.5 rotate forever, and the faster one has the higher wave. The threshold is omega = 2 sqrt(g / L), about 6.26 rad/s at the bottom. Notice we passed that threshold to the plot as energy < 2 g/L rather than guessing.

Exhibit 3: Lissajous curves

When a point moves horizontally as sin(a t + phase) and vertically as sin(b t), the path it traces is a Lissajous curve. The ratio a : b decides the shape: 1:1 gives an ellipse (a line or circle for certain phases), and ratios of small whole numbers give closed knots with a fixed number of loops. Oscilloscopes use this to compare frequencies.

A 3 by 3 grid of ratios fits this exhibit perfectly. We turn off the axes (ax.axis("off")) so only the curves show and keep the aspect equal so loops stay round.

Python A grid of Lissajous figures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The main diagonal is the 1:1, 2:2 and 3:3 pairs. They look like the same shape because a : b and 2a : 2b are the same ratio; the curve just gets traced twice or three times in the same time. Off the diagonal, count the lobes: a 1:2 curve crosses itself once like a figure eight, and the number of horizontal and vertical touches encodes the two frequencies.

Exhibit 4: the Mandelbrot set as an image

The Mandelbrot set is the set of complex numbers c for which the sequence z -> z^2 + c, starting at z = 0, never escapes to infinity. To draw it, build a grid of complex numbers (one per pixel), iterate the formula for every pixel at once, and record how many steps it took each point to escape beyond |z| > 2. Points that never escape inside our iteration budget belong to the set.

All pixels are processed in NumPy arrays; a boolean mask alive remembers which ones are still iterating, so finished pixels stop costing work. A small logarithmic correction smooths the iteration count so the colors blend instead of forming bands. The result is a plain 2D array, which is exactly what imshow wants. Points inside the set are nan, and set_bad("black") on a copy of the colormap paints them black. See Heatmaps and Images for extent and origin.

Python Render the Mandelbrot set with imshow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The black region is the set; the colored halo around it shows how fast nearby points escape. A little under a quarter of the grid lies inside. origin="lower" puts the imaginary axis pointing up as in a math textbook, and extent labels the axes in complex-plane coordinates rather than pixel numbers. Try raising max_iter or zooming by changing the range of xs and ys to look at the boundary, which has detail at every scale.

Exhibit 5: a field of invisible forces with streamplot

A vector field assigns an arrow to every point in the plane. quiver draws one arrow per sample, which gets crowded quickly. streamplot instead draws flowing lines that follow the field, so you see where it goes. Our field belongs to two electric charges of opposite sign, a positive one at x = -1.2 and a negative one at x = 1.2. Each charge contributes q * r / |r|^3, and we add the two. A small constant under the square root keeps the field finite at the charges themselves.

The streamlines are colored by the logarithm of the field strength: the field changes by orders of magnitude between near and far, so a linear color scale would hide almost everything. streamplot returns an object whose .lines attribute can be handed to fig.colorbar.

Python Electric field of two charges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Field lines leave the positive charge, curve through space and enter the negative one, the textbook dipole picture. Bright, warm colors cluster near the charges where the field is strong, and the lines fade to dark at large distances. Because the grid was made with np.mgrid and the complex-step syntax 200j, the arrays are shaped (200, 260) with y first, which is the order streamplot expects.

Exhibit 6: a filmstrip instead of an animation

An animation shows how something changes over time. On a static page, you can get most of the benefit with a filmstrip: a row of small axes, one per moment, drawn with the same code and the same limits. Our last exhibit simulates one pendulum swing and draws eight snapshots. Each frame shows the rod, the bob, and the path the bob has traveled so far as a gray trail.

All eight axes share limits (sharex=True, sharey=True) so the frames are directly comparable, and ax.axis("off") removes the frames' clutter. To make an actual animation later, you would keep the drawing code in a function and ask FuncAnimation to call it for each frame, exactly as described in the animation lesson.

Python Eight frames of a pendulum swing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

By the last frame the pendulum is nearly back where it started, so one full period of this 1.2 radian swing takes about 2.15 seconds. That is a little longer than the small-angle formula 2 pi sqrt(L / g), about 2.0 seconds, which is another nice discovery from the simulation: bigger swings are slower. The gray trail grows frame by frame, which is how your eye reads motion from still images.

Whatever you simulate, keep the physics (state, derivative, step) in plain functions that return arrays, and the plotting in other functions that take those arrays. You can then reuse the same simulation for a static figure, a filmstrip, or a FuncAnimation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the projectile code use set_aspect("equal")?

    With equal aspect, one data unit has the same length on the x and y axes, so angles and arc shapes are drawn truthfully. Without it, the arcs would be stretched.
  2. 2. What does the nan inserted when wrapping the pendulum angle accomplish?

    Matplotlib leaves a gap in a line wherever there is a nan. Without it, the wrapped curve would draw a long horizontal line connecting the two edges of the plot.
  3. 3. In the Mandelbrot code, what is the job of the boolean array alive?

    Each iteration updates z only where alive is True. Pixels that already escaped are frozen, which saves work and lets us record each pixel's escape step exactly once.
  4. 4. Why is streamplot colored by log10 of the field strength in the dipole example?

    Field strength falls off steeply with distance. A logarithm compresses that huge range so that both the strong regions near the charges and the faint far field remain visible.

Summary

  • Simulations are loops of state, derivative, step and store; Matplotlib draws the stored arrays.
  • Euler stepping is simple (projectile with drag); RK4 is far more accurate for oscillations such as the pendulum.
  • A phase portrait plots velocity against position and shows every kind of motion at once; wrap angles and break lines with nan.
  • Parametric curves like Lissajous figures come straight from plot(x(t), y(t)).
  • Fractals and fields become images: compute a 2D array, then imshow with extent and origin, or streamplot with a colored .lines object.
  • A filmstrip of identical, shared-limit axes is an honest static substitute for an animation.

Next project: Infographic Poster.