Making and reading physics plots in Python

A plot is an argument, not a decoration

Every choice you make in a figure asserts something. Connecting two measured points with a straight segment asserts that the quantity varied linearly between them. Omitting error bars asserts that the scatter you can see is the whole story.


Choosing a logarithmic axis asserts that proportional change is what matters. The craft of scientific plotting is making sure each of those assertions is one you actually intend.

Pendulum period against length, logarithmic axes

Pendulum period against length, logarithmic axes


The examples below use matplotlib with the explicit figure-and-axes interface, which is worth adopting from the start because it scales to multi-panel figures without rewriting anything.


import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 4))

Choosing the plot type

  • Measured data: use markers, not a connecting line, because you measured points and not the space between them. When each point carries an uncertainty, ax.errorbar is the right call and the error bars are part of the data, not an optional embellishment.
  • A model or fitted curve: use a continuous line evaluated on a fine grid. The contrast in style is what lets a reader tell at a glance which curve is measurement and which is theory.
  • A distribution of one variable: use a histogram. Note that a histogram discards any second variable, so it cannot show how a quantity evolves with time.
  • Categorical quantities: use bars. For uncertain point measurements against continuous time, bars are generally unsuitable because they emphasize magnitudes from a zero baseline and omit dv; numeric bar positions can still retain their time coordinates and spacing.


ax.errorbar(t, v, yerr=dv, fmt='o', capsize=3, label='measurement')
ax.plot(t_grid, v_model, '-', label='model')

Axes must carry quantity and unit

The standard physics convention names the quantity, gives its symbol, and gives the unit in parentheses:


ax.set_xlabel('Time, t (s)')
ax.set_ylabel('Speed, v (m/s)')
ax.legend()


A numerical value of a dimensional quantity is incomplete without its unit, and a reader cannot check your result, compare it with another experiment, or spot a unit-conversion error if the axis does not say what the numbers mean.


Some physical quantities are genuinely dimensionless, a refractive index, a strain, or the logarithm of a ratio, and for those the label should name the quantity and the ratio plotted rather than invent a unit.


Putting the unit only in the caption fails as soon as the figure is reproduced in slides, and putting only the unit on the axis leaves the reader guessing which quantity it belongs to.


An unnamed second series needs either a legend or direct labels so the reader can identify it.

Anatomy of a physics figure: markers with vertical uncertainty bars for the measured values, a continuous curve for the model, tick marks and numerals on both axes, axis labels carrying quantity and unit, and a legend identifying the two series.

Anatomy of a physics figure: markers with vertical uncertainty bars for the measured values, a continuous curve for the model, tick marks and numerals on both axes, axis labels carrying quantity and unit, and a legend identifying the two series.

Linearising a suspected relationship

The eye judges straight lines far better than it judges curvature, so physicists routinely transform a suspected relationship into a straight line and read the exponent or rate constant off the slope. Two cases cover most of an introductory course.


Suspected form

Plot

Slope gives

Power law, y = A xn

log(y/yref) against log(x/xref)

the exponent n

Exponential, y = A ekt

ln(y/yref) against t (semilog)

the rate constant k


The algebra behind the first row: a logarithm accepts only a dimensionless argument, so divide each variable by a fixed reference value of its own kind before transforming.


Taking logarithms of y = A xn then gives log(y/yref) = log(A xrefn/yref) + n log(x/xref), which is a straight line in the transformed variables with gradient n and intercept log(A xrefn/yref).


Taking one unit of each quantity as its reference, the usual convention, makes the plotted numbers the familiar logarithms of the values in those units; a different choice of reference shifts the intercept but never the gradient.


For the second row, ln(y/yref) = ln(A/yref) + kt is linear in t itself, not in ln(t/tref).


Choosing the wrong transformation is the commonest error here, and it is easy to guard against by writing the logarithm of the model out in full before deciding what to plot against what.

Worked example

A capacitor discharges and the voltage is expected to follow V = V0e-t/τ. Dividing by the reference voltage 1 V and taking natural logarithms gives ln[V/(1 V)] = ln[V0/(1 V)] - t/τ, so plotting ln[V/(1 V)] against t should give a straight line of gradient -1/τ.


slope, intercept = np.polyfit(t, np.log(V), 1)
tau = -1.0 / slope
V0 = np.exp(intercept)


The NumPy arrays hold numerical values in the declared units: t contains the times in seconds and V the voltages in volts, so np.log(V) returns the values of ln[V/(1 V)] and V0 comes out as a number of volts.


Suppose the fit returns a gradient of -0.25 s-1 and an intercept of 2.30. Then τ = -1/(-0.25) = 4.0 s, and V0 = e2.30 V = 9.97 V.


Two checks are worth making every time. First, the units: a gradient in s-1 must invert to a time, so an answer of 0.25 s would have the arithmetic backwards.


Second, the intercept is the logarithm of the amplitude expressed in volts, so it must be exponentiated and then given its unit rather than used directly.

Reading a figure critically

  • Check the plotted range. Autoscaling shows whatever was passed in. A model that hugs the data over a short initial interval may diverge badly over the full measured range, and a figure restricted to that interval conceals the disagreement.
  • Judge agreement against the error bars, not by eye. Two curves that look close on a linear axis can disagree by many standard uncertainties. Plotting the residuals, the measured value minus the model value, in a second panel against the same horizontal axis makes the comparison explicit and is the honest way to display a fit.
  • Watch the axis scale. A quantity spanning several orders of magnitude is unreadable on a linear axis, where every small value is crushed against zero.
  • Distinguish fitted from extrapolated portions. An extrapolated portion must be clearly distinguished and not presented as data-supported fit agreement.

A checklist before saving

fig.tight_layout()
fig.savefig('discharge.png', dpi=200)


  • Both axes labelled with quantity and unit, or, for a dimensionless axis such as log(V/Vref), with the ratio that was plotted.
  • Measured points shown as markers with their uncertainties.
  • Models shown as lines, on a grid fine enough to look smooth.
  • A legend or direct labels for each otherwise unidentified series.
  • Axis limits covering the full range of the data.
  • Scales chosen so the structure you are claiming is actually visible.

A student measures the speed of a falling object at ten separate instants, and each speed measurement has an associated uncertainty stored in the array dv. The times are in t and the speeds in v.

Which matplotlib call best represents these data?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A student times a simple pendulum at five different lengths and plots log10(T / s) against log10(L / m). The accompanying chart shows the five points, whose coordinates are

log10(L / m)

log10(T / s)

-1.0000

-0.1977

-0.6990

-0.0471

-0.3979

0.1034

-0.0969

0.2539

0.2041

0.4044

The points lie on a straight line. Calculate its gradient, giving your answer to three decimal places.

Give your answer as a number.

Anatomy of a physics figure: markers with vertical uncertainty bars for the measured values, a continuous curve for the model, tick marks and numerals on both axes, axis labels carrying quantity and unit, and a legend identifying the two series.

Anatomy of a physics figure: markers with vertical uncertainty bars for the measured values, a continuous curve for the model, tick marks and numerals on both axes, axis labels carrying quantity and unit, and a legend identifying the two series.

Pendulum period against length, logarithmic axes

Pendulum period against length, logarithmic axes

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A student expects the speed of a damped object to decay exponentially, v = v0e-t/τ, and wants a plot on which the data should fall on a straight line so that τ can be found from the gradient.

Which transformation achieves this, and what does the resulting gradient give?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors