Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 57 ยท Projects

Project: A 3D Sine Wave Surface

Build a rippling 3D sine wave surface in Matplotlib: meshgrid maths, travelling waves as a filmstrip, two-source interference, camera angles and an animation for your computer.

Drop a pebble in a pond and rings spread outwards. Plot the height of the water over the pond and you get a 3D surface that rises and falls like a sine wave in every direction. This project builds that picture step by step, then makes it move, and ends with the beautiful pattern two pebbles make together.

You will practise: turning a formula into a grid with meshgrid, drawing plot_surface with colour and a floor contour, controlling the camera, capturing time as a filmstrip of frames, combining two waves (interference), and writing the code for a real animation. Along the way you will see the mathematics of waves in a form you can look at. If 3D axes are new to you, read 3D Plots first.

flowchart LR
    A["1. Grid<br/>meshgrid x, y"] --> B["2. Formula<br/>z = sin(r)"]
    B --> C["3. Surface<br/>plot_surface + camera"]
    C --> D["4. Time<br/>z = sin(r - wt)"]
    D --> E["5. Two sources<br/>interference"]
    E --> F["6. Animate<br/>FuncAnimation"]

Every step changes one thing: the formula, the colours, the time or the number of sources.

Step 1: A grid and a formula

A surface needs a height z for every (x, y) position on a grid. np.linspace makes the positions along each axis and np.meshgrid turns them into two 2D arrays X and Y that hold the coordinates of every grid point. A ripple depends only on the distance from the centre, r = sqrt(xยฒ + yยฒ), so the height is z = sin(r).

Python Step 1: the first ripple

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 result is a set of rings that rise and fall with a constant wavelength of about 2ฯ€ (6.3 units). Every point at the same distance from the centre has the same height, which is why the pattern is circular. If your picture looks jagged, increase the number of points in linspace; if it renders slowly, reduce them or add rstride=2, cstride=2.

Step 2: Fading the ripple and choosing a camera

A real water ripple loses energy as it spreads. Dividing by a growing function of the distance makes the rings fade: z = sin(r) / (1 + 0.3 r). Then we can improve the picture: set the vertical range with set_zlim, pick the camera with view_init(elev, azim) and draw the floor contour with contourf at a fixed offset, so that the top view is visible even in a still image.

Python Step 2: a fading ripple with a floor contour

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 two settings that matter most for a good 3D picture are set_zlim (so the height range is the same in every picture you will compare) and view_init. A low elevation (10 to 20 degrees) shows the waves like a landscape; a high one looks down on them. The floor contour acts as a map: you can see the rings even where the surface hides them.

Step 3: Making time visible

A wave moves. In a formula, a travelling wave is z = sin(r - ฯ‰t): at time t the crest that was at distance r is now at r + ฯ‰t, so the rings expand outwards. A still image cannot show motion, but a filmstrip of the same surface at several times can: draw the same plot at t = 0, 1, 2, ... with identical axes and watch one ring travel.

Python Step 3: six moments of the travelling ripple

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.

Compare the panels: the ring pattern slides outwards while the shape stays the same. The printed numbers confirm it: the crest moves away from the middle by about 0.8 units every 0.4 time units, which is the wave speed of 2. The fixed zlim and colour limits (vmin=-1, vmax=1) are what make the panels comparable; if each panel scaled itself, the fading wave would look the same height all the time.

Step 4: Two sources and interference

Now throw in two pebbles. Waves from two sources add up: where two crests meet, the water rises twice as high (constructive interference); where a crest meets a trough, the surface stays flat (destructive interference). In code, compute the distance from each source and add the two waves.

Python Step 4: interference of two ripples

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.

In the top view, curved bands radiate from the middle between the two sources: along each band the two waves arrive out of step and cancel, in between they reinforce each other. This is the famous two-source interference pattern. Change the source distance (the 3 values) or the wave number k and watch the bands move.

Step 5: Animating on your computer

The browser shows still images, so the animation is read-only code for your own machine. A 3D surface cannot be updated in place the way a bar chart can: each frame you remove the old surface and draw a new one. FuncAnimation calls your function once per frame with the frame number:

Python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

x = np.linspace(-8, 8, 80)
X, Y = np.meshgrid(x, x)
R = np.sqrt(X**2 + Y**2)

fig = plt.figure(figsize=(7, 5))
ax = fig.add_subplot(1, 1, 1, projection="3d")
ax.set_zlim(-1, 1)
ax.set_box_aspect((1, 1, 0.5))
surface = [ax.plot_surface(X, Y, np.zeros_like(R), cmap="viridis", vmin=-1, vmax=1)]

def update(frame):
    surface[0].remove()                                   # drop last frame's surface
    Z = np.sin(R - 0.25 * frame) / (1 + 0.3 * R)           # the travelling wave
    surface[0] = ax.plot_surface(X, Y, Z, cmap="viridis", vmin=-1, vmax=1, linewidth=0)
    ax.view_init(elev=30, azim=-60 + frame * 0.5)          # slowly orbit the camera
    return surface

anim = FuncAnimation(fig, update, frames=96, interval=50)
plt.show()                                                 # or: anim.save("ripple.gif", writer="pillow", fps=20)

Three things make this code work well. surface[0].remove() prevents the Axes from filling up with hundreds of old surfaces and slowing to a crawl. A fixed set_zlim stops the box from jumping around. And keeping anim in a variable stops Python from discarding the animation before it plays. A grid of 80 by 80 points renders at a comfortable speed; 200 by 200 will be slow because each frame redraws 40,000 polygons. See Animation Concepts for saving GIFs and videos.

Extension ideas

  • Turn the ripple into a standing wave: z = sin(kx) * cos(ฯ‰t), which does not travel but oscillates in place.
  • Replace sin(r) with a function of x and y separately, such as sin(x) * cos(y), and describe the "egg-box" it creates.
  • Use plot_wireframe or plot_trisurf instead of plot_surface and compare how they look.
  • Add a damped wave exp(-0.2 * r) * sin(2r) and fit the right elev and azim to show it clearly.
  • Three sources at the corners of a triangle: how many calm lines do you see?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does np.meshgrid(x, y) return for 1D arrays x and y?

    meshgrid builds X and Y with the same 2D shape so that a formula in X and Y can be evaluated at every grid point at once.
  2. 2. Why is z = sin(sqrt(X2 + Y2)) circular?

    All points at the same distance r have the same height, so the surface has rotational symmetry around the centre.
  3. 3. In the travelling wave z = sin(r - w*t), what happens as t grows?

    A crest satisfies r - wt = constant, so r = constant + wt: it moves outwards at speed w.
  4. 4. Why set the same zlim and colour limits in every panel of the filmstrip?

    If each panel picked its own range, a fading wave would always fill the panel, hiding the fading. Fixed limits show real changes.
  5. 5. What must you do in each frame of a 3D surface animation?

    Surfaces cannot be updated like bar heights. Removing the old surface avoids piling up artists, which would make the animation slower every frame.

Summary

  • A surface z = f(x, y) needs a meshgrid, a formula on the grid arrays and ax.plot_surface(X, Y, Z).
  • Use the distance from a centre, r = sqrt(xยฒ + yยฒ), for ripples; divide by 1 + a*r to fade them.
  • set_zlim, set_box_aspect, view_init and a floor contourf make a 3D picture readable.
  • A travelling wave is sin(r - w*t); a filmstrip with fixed limits shows time in a still page.
  • Waves from several sources add up, which creates interference bands; the top-view heatmap shows them best.
  • For animations, remove the old surface in each frame, keep the zlim fixed and keep a reference to the animation.

Next: Project: Visualizing a Pandemic Time Series turns to real-world-style time series.