Draw into your own figure

Use this when several plots should stand in one figure, or when a plot needs a title, a size or a mark of your own.

Steps

  1. Make the figure and its axes with matplotlib: figure, (left, right) = plt.subplots(1, 2).

  2. Pass the axes to plot with ax=. The plot is drawn there, and no new figure is opened.

  3. Change what you like on the axes afterwards. plot returns them too.

Example

A wave of one frequency from a small source: the wave at one instant beside its amplitude.

import matplotlib.pyplot as plt
import sympy as sp
import pdemagic as pm

x, y = sp.symbols("x y", real=True)
w = sp.Function("w")(x, y)

source = sp.exp(-8 * (x**2 + y**2))
waves = pm.solve(
    pm.Problem(sp.Eq(pm.laplacian(w) + 36 * w, -source), domain=pm.FreeSpace(x, y))
)

figure, (left, right) = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
drawn = waves.plot(part="real", ax=left)
waves.plot(ax=right)
left.set_title("The wave at one instant", loc="left")
right.set_title("Its amplitude", loc="left")
right.plot([0], [0], marker="+", color="black")  # the source

assert drawn is left
assert len(figure.axes) == 4  # two plots, each with its colour bar
The figure that the example above draws. The figure that the example above draws.

Notes

  • Without ax= every call of plot opens a figure of its own.

  • plot returns the matplotlib axes that it drew into, so a single plot can be changed in the same way: solution.plot().set_title("...").

  • A plot of a field brings its colour bar, which takes its room from the axes that you gave.

  • theme="dark" draws for a dark background. Give it to every plot of a figure.

  • Save the figure with matplotlib: figure.savefig("waves.png").

  • Plotting needs matplotlib, which pip install "pdemagic[plot]" brings. pdemagic imports it only when a plot is asked for.

  • For anything that plot does not draw, take the arrays: see Get the arrays and the grid.

  • Plotting explains what plot draws and its arguments, and the reference lists them.