---
title: Plotting signals with matplotlib
heading: A plot is how a calculation shows you it's right
eyebrow: A4 · Lesson 32 · Plotting signals
xp: 40
---

::: hook
A column of 2000 numbers tells you almost nothing. The same numbers drawn as a curve tell you at a glance whether a capacitor is charging, how fast, and whether you got a sign wrong somewhere. Engineers plot everything, early and often, and in Python that's matplotlib.
:::

::: predict
## You run `plt.plot(t, v)` where `t` has 1000 values and `v` has 999. What happens?

- [ ] The plot drops the extra time
- [ ] The last point repeats
- [x] An error: the two arrays must have the same length
- [ ] It plots `v` against its index instead

::: reveal
An error, something like "x and y must have same first dimension". `plt.plot(x, y)` pairs the values up one to one, so both arrays need the same length. When this happens, it usually means one array was built with a different number of points, which is worth knowing about.
:::
:::

::: nameit
## The few commands that cover most plots

```
import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 5e-3, 500)
v = 5 * np.exp(-t / 1e-3)

plt.plot(t * 1e3, v, label='v(t)')   # x, y, and a name for the legend
plt.xlabel('t (ms)')
plt.ylabel('v (V)')
plt.axvline(1, linestyle='--')        # a vertical line at t = 1 ms
plt.legend()
plt.grid(True)
```

- **`plt.plot(x, y)`** draws a line through the points. Call it again to add more lines to the same axes.
- **Labels with units** on both axes, always. Scaling the data (`t * 1e3`) and labeling the axis `ms` is cleaner than an axis of tiny numbers.
- **`label=` and `plt.legend()`** name the lines.
- **`plt.axvline(x)` and `plt.axhline(y)`** draw reference lines, such as a time constant or a threshold.
- **Log axes:** `plt.semilogx`, `plt.semilogy` and `plt.loglog` work like `plt.plot` with one or both axes logarithmic, for Bode plots and anything spanning decades.
- **`plt.subplot(2, 1, 1)`** starts the first of two stacked panels; `plt.subplot(2, 1, 2)` the second.

In these labs the figure appears under your code when it runs.
:::

::: example
## Plot a voltage and a current on the same axes and tell them apart.

::: solution
1. **Scale the current to a readable size.** Plotting $5 \times i$ puts both on a readable scale.
2. **Label each line.** The label says the current is scaled, the way a scope's current probe setting does.

```
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0, 0.04, 800)
v = 10 * np.cos(2 * np.pi * 50 * t)
i = 2 * np.cos(2 * np.pi * 50 * t - np.pi / 3)
plt.plot(t * 1e3, v, label="v (V)")
plt.plot(t * 1e3, 5 * i, label="5 × i (A)")
plt.xlabel("t (ms)")
plt.legend()
```

3. **Read the plot.** The current visibly lags by 60°.

**Answer:** plot $v$ and $5 \times i$ on the same axes with labels and a legend; the current lags the voltage by 60°.
:::
:::

::: example
## Mark the time constant on a discharge curve.

::: solution
1. **Plot the discharge.** 12 V decaying with $\tau$ = 4.7 ms, out to $5\tau$.
2. **Add the reference lines.** A dashed vertical line at $t = \tau$ and a dotted horizontal line at $12e^{-1}$.

```
tau = 4.7
t = np.linspace(0, 5 * tau, 300)
plt.plot(t, 12 * np.exp(-t / tau))
plt.axvline(tau, linestyle="--", color="grey")
plt.axhline(12 * np.exp(-1), linestyle=":", color="grey")
plt.xlabel("t (ms)"); plt.ylabel("v (V)")
```

3. **Read the crossing.** The two reference lines cross on the curve at $(\tau, 0.368 \times 12)$, the defining point of a time constant.

**Answer:** mark the time constant with `axvline` at $\tau$ and `axhline` at $0.368 \times 12$ V; they meet on the curve.
:::
:::

::: check
kind: python
given: V0 = 3..12 int; tau = 1..9 int

## Plot a capacitor's discharge, $v = \given{V0}\,e^{-t/\tau}$ with $\tau$ = {tau} ms, from 0 to $5\tau$, with time in milliseconds on the x axis. Label both axes and mark $t = \tau$ with a dashed vertical line.

`V0` = {V0} (volts) and `tau` = {tau} (milliseconds) are already defined.

```python starter
import numpy as np
import matplotlib.pyplot as plt

t_ms = np.linspace(0, 5 * tau, 400)   # time in ms
v = V0 * np.ones_like(t_ms)          # replace: the discharge curve

plt.plot(t_ms, v)
# label the axes, and mark t = tau
```

```python solution
import numpy as np
import matplotlib.pyplot as plt

t_ms = np.linspace(0, 5 * tau, 400)
v = V0 * np.exp(-t_ms / tau)

plt.plot(t_ms, v)
plt.xlabel('t (ms)')
plt.ylabel('v (V)')
plt.axvline(tau, linestyle='--')
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
ax = plt.gca()
lines = ax.get_lines()
curves = [l for l in lines if len(l.get_xdata()) > 2]
assert curves, "Plot the discharge curve with plt.plot(t_ms, v)."
x, y = np.asarray(curves[0].get_xdata(), float), np.asarray(curves[0].get_ydata(), float)
assert np.allclose(y, V0 * np.exp(-x / tau), rtol=1e-6), "The curve should be V0·exp(-t/tau), with t and tau both in ms."
assert ax.get_xlabel() and ax.get_ylabel(), "Label both axes, with units: plt.xlabel('t (ms)') and plt.ylabel('v (V)')."
marks = [l for l in lines if len(l.get_xdata()) == 2 and np.allclose(np.asarray(l.get_xdata(), float), tau)]
assert marks, "Mark t = tau with plt.axvline(tau, linestyle='--')."
```

::: right
Right. At the dashed line the curve has fallen to 37% of where it started.
:::
:::

::: check
kind: python
given: A = 1..5 int; p = 30 | 45 | 60 | 90

## On one set of axes, plot $\given{A}\cos(2\pi \cdot 50\,t)$ and $\given{A}\cos(2\pi \cdot 50\,t - \given{p}°)$ over 40 ms, with time in ms, and add a legend naming them `v1` and `v2`.

```python starter
import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 0.04, 800)
v1 = A * np.cos(2 * np.pi * 50 * t)
v2 = 0 * t   # replace: delayed by p degrees

plt.plot(t * 1e3, v1)
# plot v2, label both lines, add a legend
plt.xlabel('t (ms)')
plt.ylabel('v (V)')
```

```python solution
import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 0.04, 800)
v1 = A * np.cos(2 * np.pi * 50 * t)
v2 = A * np.cos(2 * np.pi * 50 * t - np.radians(p))

plt.plot(t * 1e3, v1, label='v1')
plt.plot(t * 1e3, v2, label='v2')
plt.legend()
plt.xlabel('t (ms)')
plt.ylabel('v (V)')
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
ax = plt.gca()
assert np.allclose(v2, A * np.cos(2 * np.pi * 50 * t - p * np.pi / 180)), "v2 should be delayed by p degrees: convert with np.radians(p), and subtract it inside the cosine."
assert not np.allclose(v2, A * np.cos(2 * np.pi * 50 * t - p)), "np.cos takes radians, so convert p first."
assert len([l for l in ax.get_lines() if len(l.get_xdata()) > 2]) >= 2, "Plot both v1 and v2."
assert ax.get_legend() is not None, "Add a legend: give each plot a label= and call plt.legend()."
names = [t.get_text() for t in ax.get_legend().get_texts()]
assert 'v1' in names and 'v2' in names, "Name the lines v1 and v2 with label='v1' and label='v2'."
```

::: right
Right. The second wave's peaks come {p}° of a cycle later.
:::
:::

::: check
kind: choice

## Which call draws a Bode magnitude plot, with frequency on a log axis and decibels on a linear one?

- [ ] `plt.loglog(f, mag_db)`
- [x] `plt.semilogx(f, mag_db)`
- [ ] `plt.semilogy(f, mag_db)`
- [ ] `plt.plot(np.log(f), mag_db)` is the only way

::: right
Right. Decibels are already logarithmic, so only the frequency axis needs a log scale.
:::

::: misses
- [1] Decibels are already a log measure, so the y axis stays linear. `loglog` would also fail on negative dB values.
- [3] That puts the log scale on the y axis. Frequency is on x.
- [4] That works numerically, but `semilogx` keeps the real frequencies on the axis labels.
:::
:::

::: check
kind: python
given: R = 1k..10k E12; k = 1..5 int

## The starter has ten measured points, voltages `V` and currents `I` in amps, from a resistor of about {R} Ω. Plot the points as dots with no line joining them (`'o'`), then the straight line $I = V/R$ through them as a solid line over the same voltages. Label both axes with units.

```python starter
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(k)
V = np.linspace(0.5, 5, 10)
I = V / R * (1 + rng.normal(0, 0.02, 10))
plt.plot(V, I)
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(k)
V = np.linspace(0.5, 5, 10)
I = V / R * (1 + rng.normal(0, 0.02, 10))
plt.plot(V, I, 'o', label='measured')
plt.plot(V, V / R, '-', label='V/R')
plt.xlabel('V (V)')
plt.ylabel('I (A)')
plt.legend()
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
ax = plt.gca()
lines = ax.get_lines()
dots = [l for l in lines if l.get_marker() not in (None, '', 'None', ' ') and l.get_linestyle() in ('None', '', ' ')]
assert dots, "Plot the measurements as dots with no line: plt.plot(V, I, 'o')."
assert np.allclose(np.asarray(dots[0].get_ydata(), float), np.asarray(I, float)), "The dots should be the measured currents I against V."
fits = [l for l in lines if l.get_linestyle() == '-' and np.allclose(np.asarray(l.get_ydata(), float), np.asarray(l.get_xdata(), float) / R)]
assert fits, "Add the line I = V/R as a solid line: plt.plot(V, V / R, '-')."
assert ax.get_xlabel() and ax.get_ylabel(), "Label both axes with their units."
```

::: right
Right. Measurements are dots, because only the measured points are known; a model is a line, because it's defined everywhere. Joining measured points with lines suggests you know what happened between them.
:::
:::

::: check
kind: python
given: bits = 2 | 3 | 4

## Plot the output of a `bits`-bit ADC ({bits} bits, so codes 0 to `2**bits - 1`, full scale 1 V) for an input ramp `vin` from 0 to 1 V over 1 ms, as a staircase: use `plt.step(t_ms, code, where='post')`, where `code` is `np.floor(vin * 2**bits)` clipped to the top code. Label both axes.

```python starter
import numpy as np
import matplotlib.pyplot as plt
t_ms = np.linspace(0, 1, 500)
vin = t_ms
code = vin * 2**bits
plt.plot(t_ms, code)
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
t_ms = np.linspace(0, 1, 500)
vin = t_ms
code = np.minimum(np.floor(vin * 2**bits), 2**bits - 1)
plt.step(t_ms, code, where='post')
plt.xlabel('t (ms)')
plt.ylabel('ADC code')
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
ax = plt.gca()
lines = ax.get_lines()
steps = [l for l in lines if l.get_drawstyle() == 'steps-post']
assert steps, "Draw a staircase with plt.step(t_ms, code, where='post')."
y = np.asarray(steps[0].get_ydata(), float)
x = np.asarray(steps[0].get_xdata(), float)
assert np.allclose(y, np.minimum(np.floor(x * 2**bits), 2**bits - 1)), f"The codes should be floor(vin * {2**bits}), with the last one clipped to {2**bits - 1}."
assert ax.get_xlabel() and ax.get_ylabel(), "Label both axes."
```

::: right
Right. A converter's output holds each code until the input crosses the next threshold, so a staircase drawn "post" shows it honestly. A straight line through the codes would suggest values the ADC can't produce.
:::
:::

::: check
kind: choice

## You want the y axis to run from −1 to 1 whatever the data is. Which call does it?

- [x] `plt.ylim(-1, 1)`
- [ ] `plt.axis('equal')`
- [ ] `plt.yscale('linear')`
- [ ] `plt.ylabel(-1, 1)`

::: right
Right. `plt.ylim` fixes the y axis limits. Fixing limits matters when you compare several plots: the same scale on each keeps the eye honest.
:::

::: misses
- [2] That makes one unit the same length on both axes. It doesn't set the limits.
- [3] That chooses a linear scale (the default). The limits are set separately.
- [4] `ylabel` sets the axis label text.
:::
:::

::: explain
## Why do engineers scale data before plotting it, for example plotting `t * 1e3` against an axis labeled "t (ms)"?

::: model
An axis reading 0, 0.001, 0.002 is hard to read and easy to misread by a factor of a thousand. Scaling the numbers to a sensible prefix and saying so in the label gives tick marks like 0, 1, 2 ms that you can read at a glance and compare directly with datasheets and scopes, which use the same prefixes. The data are the same; only the units they're shown in change.
:::
:::

::: practice

::: check
kind: python
given: V0 = 2..9 int; tau = 1..5 int

## Plot the charging curve $\given{V0}(1 - e^{-t/\tau})$, $\tau$ = {tau} ms, from 0 to $5\tau$ ms, and draw a dashed horizontal line at {V0} V.

```python starter
import numpy as np
import matplotlib.pyplot as plt

t_ms = np.linspace(0, 5 * tau, 300)
v = 0 * t_ms
plt.plot(t_ms, v)
plt.xlabel('t (ms)')
plt.ylabel('v (V)')
```

```python solution
import numpy as np
import matplotlib.pyplot as plt

t_ms = np.linspace(0, 5 * tau, 300)
v = V0 * (1 - np.exp(-t_ms / tau))
plt.plot(t_ms, v)
plt.axhline(V0, linestyle='--')
plt.xlabel('t (ms)')
plt.ylabel('v (V)')
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
lines = plt.gca().get_lines()
curve = [l for l in lines if len(l.get_xdata()) > 2]
assert curve and np.allclose(np.asarray(curve[0].get_ydata(), float), V0 * (1 - np.exp(-np.asarray(curve[0].get_xdata(), float) / tau))), "The curve should be V0·(1 − exp(−t/tau))."
assert [l for l in lines if len(l.get_ydata()) == 2 and np.allclose(np.asarray(l.get_ydata(), float), V0)], "Add plt.axhline(V0, linestyle='--')."
```
:::

::: check
kind: python
given: R = 1k..10k E12 Ω; C = 10n..100n E6 F

## Make a Bode magnitude plot in dB of $H = 1/(1 + j2\pi f RC)$ from 10 Hz to 1 MHz, with a log frequency axis. Store the dB values in `mag_db`.

```python starter
import numpy as np
import matplotlib.pyplot as plt

f = np.logspace(1, 6, 300)
mag_db = 0 * f
plt.plot(f, mag_db)
```

```python solution
import numpy as np
import matplotlib.pyplot as plt

f = np.logspace(1, 6, 300)
H = 1 / (1 + 1j * 2 * np.pi * f * R * C)
mag_db = 20 * np.log10(np.abs(H))
plt.semilogx(f, mag_db)
plt.xlabel('f (Hz)')
plt.ylabel('|H| (dB)')
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
assert np.allclose(mag_db, 20 * np.log10(np.abs(1 / (1 + 1j * 2 * np.pi * f * R * C)))), "mag_db should be 20·log10|H|."
assert plt.gca().get_xscale() == 'log', "Use plt.semilogx so the frequency axis is logarithmic."
```
:::
:::
