---
title: Plots that communicate
heading: Log axes, subplots and a Bode plot from scratch
eyebrow: A4 · Lesson 33 · Plots that communicate
xp: 40
---

::: hook
A plot is an argument. A frequency response on a linear axis squashes everything below 1 kHz into one pixel; on a log axis every decade gets equal room and the roll-off becomes a straight line. Magnitude and phase share a frequency axis, so they belong stacked on one figure. Every axis needs a label with units, and every line on a shared axis needs a name. This lesson is the handful of matplotlib tools that turn a correct calculation into a plot someone can read.
:::

::: predict
## A low-pass filter's gain in dB is plotted against frequency on a **log** frequency axis. Far above the corner, what shape is the curve?

- [ ] A curve that bends ever more steeply
- [x] A straight line sloping down
- [ ] A horizontal line
- [ ] An exponential decay

::: reveal
A straight line: −20 dB for every factor of 10 in frequency. Decibels are a log of the gain and the axis is a log of frequency, so a power law becomes a line, as in A1. That's why datasheets always use log axes for frequency.
:::
:::

::: nameit
## Figures and axes

`plt.plot` draws on the current axes, which is fine for one plot. For more than one, ask for them explicitly:

```
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(6, 5))
ax1.plot(f, mag_db)
ax2.plot(f, phase_deg)
```

`sharex=True` keeps the two frequency axes lined up. Each `ax` has the same methods: `plot`, `set_xlabel`, `set_ylabel`, `set_title`, `set_xscale`, `set_xlim`, `grid`, `legend`, `axvline`, `axhline`.

## Log axes

| Call | Axes |
|---|---|
| `ax.set_xscale("log")` or `plt.semilogx(...)` | log $x$, linear $y$: Bode plots |
| `plt.semilogy(...)` | linear $x$, log $y$: exponential decays, error rates |
| `plt.loglog(...)` | both log: power laws, impedance against frequency |

Make log-spaced data with `np.logspace(1, 6, 500)`: 500 points from $10^1$ to $10^6$, evenly spaced in log.

## Labels, legends and reference lines

```
ax.set_xlabel("f (Hz)")
ax.set_ylabel("|H| (dB)")
ax.plot(f, h1, label="first order")
ax.plot(f, h2, label="second order")
ax.legend()
ax.axvline(fc, linestyle="--", color="grey")   # mark the corner
ax.grid(True, which="both")                    # grid lines on every decade
```

## A checklist

- Every axis labeled, with units.
- Log axes for anything spanning more than about a decade.
- Several lines on one axis: a legend, or a label next to each line.
- Reference lines for the numbers that matter (a corner, a limit, a spec).
- Shared axes for quantities that share a variable.
:::

::: example
## Plot an RC low-pass's Bode plot, magnitude and phase, with the corner marked.

::: solution
1. **Compute the transfer function on a log grid.** `np.abs` and `np.angle` work on complex arrays, so the transfer function is one line.
2. **Plot magnitude and phase on shared axes.** Two `semilogx` subplots, with a dashed line at the corner on each.

```
import numpy as np
import matplotlib.pyplot as plt
fc = 1000
f = np.logspace(1, 5, 400)
H = 1 / (1 + 1j * f / fc)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.semilogx(f, 20 * np.log10(np.abs(H)))
ax1.set_ylabel("|H| (dB)")
ax2.semilogx(f, np.degrees(np.angle(H)))
ax2.set_ylabel("phase (°)")
ax2.set_xlabel("f (Hz)")
for ax in (ax1, ax2):
    ax.axvline(fc, linestyle="--", color="grey")
    ax.grid(True, which="both")
```

**Answer:** two stacked `semilogx` plots, the magnitude in dB above the phase in degrees, with the 1 kHz corner marked on both.
:::
:::

::: example
## Show a capacitor's and an inductor's impedance against frequency on one plot.

::: solution
1. **Compute both impedances.**
   $$|Z_C| = \frac{1}{2\pi fC}, \quad |Z_L| = 2\pi fL$$
2. **Plot them on log-log axes.**

```
f = np.logspace(1, 7, 300)
ZC = 1 / (2 * np.pi * f * 100e-9)
ZL = 2 * np.pi * f * 1e-3
plt.loglog(f, ZC, label="100 nF")
plt.loglog(f, ZL, label="1 mH")
plt.xlabel("f (Hz)"); plt.ylabel("|Z| (Ω)"); plt.legend()
```

3. **Read the lines.** On log-log axes both are straight lines, slopes −1 and +1.
4. **Find the crossing.** They cross at the resonant frequency:
   $$\begin{aligned} f_0 &= \frac{1}{2\pi\sqrt{LC}} \\ &= 15.9\ \text{kHz} \end{aligned}$$

**Answer:** a `loglog` plot shows two straight lines, slopes −1 and +1, that cross at 15.9 kHz.
:::
:::

::: check
kind: python
given: fc = 100 | 1000 | 5000

## Plot an RC low-pass's gain in dB, $20\log_{10}|1/(1 + jf/f_c)|$, against `f` on a log frequency axis, with `fc` = {fc} Hz. Label the axes with units.

```python starter
import numpy as np
import matplotlib.pyplot as plt
f = np.logspace(0, 6, 500)
H = 1 / (1 + 1j * f / fc)
plt.plot(f, np.abs(H))
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
f = np.logspace(0, 6, 500)
H = 1 / (1 + 1j * f / fc)
plt.semilogx(f, 20 * np.log10(np.abs(H)))
plt.xlabel("f (Hz)")
plt.ylabel("|H| (dB)")
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
ax = plt.gca()
lines = [l for l in ax.get_lines() if len(l.get_xdata()) > 2]
assert lines, "Plot the gain against f."
x, y = np.asarray(lines[0].get_xdata(), float), np.asarray(lines[0].get_ydata(), float)
assert np.allclose(y, 20 * np.log10(1 / np.sqrt(1 + (x / fc)**2)), atol=1e-6), "Plot the gain in dB: 20·log10(|H|)."
assert ax.get_xscale() == "log", "Use a log frequency axis: plt.semilogx, or plt.xscale('log')."
assert ax.get_xlabel() and ax.get_ylabel(), "Label both axes, with units."
```
:::

::: check
kind: python
given: fc = 200 | 500 | 1000 | 2000 | 5000

## Make a figure with two stacked subplots sharing the frequency axis: gain in dB on top and phase in degrees below, both with log frequency axes, for the RC low-pass with `fc` = {fc} Hz. Label each $y$ axis.

```python starter
import numpy as np
import matplotlib.pyplot as plt
f = np.logspace(1, 6, 400)
H = 1 / (1 + 1j * f / fc)
plt.semilogx(f, 20 * np.log10(np.abs(H)))
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
f = np.logspace(1, 6, 400)
H = 1 / (1 + 1j * f / fc)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.semilogx(f, 20 * np.log10(np.abs(H)))
ax1.set_ylabel("|H| (dB)")
ax2.semilogx(f, np.degrees(np.angle(H)))
ax2.set_ylabel("phase (°)")
ax2.set_xlabel("f (Hz)")
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
axes = plt.gcf().axes
assert len(axes) == 2, "Make two subplots: fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)."
top, bottom = sorted(axes, key=lambda a: -a.get_position().y0)
def curve(ax):
    ls = [l for l in ax.get_lines() if len(l.get_xdata()) > 2]
    assert ls, "Each subplot needs a curve."
    return np.asarray(ls[0].get_xdata(), float), np.asarray(ls[0].get_ydata(), float)
x, y = curve(top)
assert np.allclose(y, -10 * np.log10(1 + (x / fc)**2), atol=1e-6), "The top subplot should be the gain in dB."
x, y = curve(bottom)
assert np.allclose(y, -np.degrees(np.arctan(x / fc)), atol=1e-6), "The bottom subplot should be the phase in degrees: np.degrees(np.angle(H))."
assert top.get_xscale() == "log" and bottom.get_xscale() == "log", "Both frequency axes should be log."
assert top.get_ylabel() and bottom.get_ylabel(), "Label each y axis."
```
:::

::: check
kind: python
given: C = 10 | 100; L = 1 | 10

## On log-log axes, plot the impedance sizes of a `C` = {C} nF capacitor and an `L` = {L} mH inductor from 10 Hz to 10 MHz, with a legend naming them `"C"` and `"L"`. Set `fx` to the frequency where they're equal.

```python starter
import numpy as np
import matplotlib.pyplot as plt
f = np.logspace(1, 7, 300)
fx = 0
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
f = np.logspace(1, 7, 300)
plt.loglog(f, 1 / (2 * np.pi * f * C * 1e-9), label="C")
plt.loglog(f, 2 * np.pi * f * L * 1e-3, label="L")
plt.xlabel("f (Hz)")
plt.ylabel("|Z| (Ω)")
plt.legend()
fx = 1 / (2 * np.pi * np.sqrt(L * 1e-3 * C * 1e-9))
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
ax = plt.gca()
assert ax.get_xscale() == "log" and ax.get_yscale() == "log", "Use plt.loglog for both axes."
leg = ax.get_legend()
assert leg is not None and {t.get_text() for t in leg.get_texts()} >= {"C", "L"}, "Add a legend with labels 'C' and 'L'."
assert abs(fx - 1 / (2 * np.pi * np.sqrt(L * 1e-3 * C * 1e-9))) < 1e-6 * fx, "fx should be 1/(2π√(LC)), where the lines cross."
```
:::

::: check
kind: python
given: R = 10 | 22 | 47; Vp = 5 | 10

## On one figure, plot a voltage $v = \given{Vp}\sin(2\pi \cdot 50\,t)$ V on the left y axis and the current $i = v/R$ through `R` = {R} Ω on a second y axis made with `ax.twinx()`, both against time in ms over 40 ms. Label each y axis with its unit.

```python starter
import numpy as np
import matplotlib.pyplot as plt
t_ms = np.linspace(0, 40, 800)
v = Vp * np.sin(2 * np.pi * 50 * t_ms / 1000)
plt.plot(t_ms, v)
plt.plot(t_ms, v / R)
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
t_ms = np.linspace(0, 40, 800)
v = Vp * np.sin(2 * np.pi * 50 * t_ms / 1000)
fig, ax = plt.subplots()
ax.plot(t_ms, v, color='C0')
ax.set_xlabel('t (ms)')
ax.set_ylabel('v (V)')
ax2 = ax.twinx()
ax2.plot(t_ms, v / R, color='C1')
ax2.set_ylabel('i (A)')
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
axes = plt.gcf().get_axes()
assert len(axes) >= 2, "Make a second y axis with ax2 = ax.twinx()."
def curve(a):
    ls = [l for l in a.get_lines() if len(l.get_xdata()) > 2]
    return np.asarray(ls[0].get_ydata(), float) if ls else None
ys = [curve(a) for a in axes]
vs = [y for y in ys if y is not None and np.isclose(np.max(y), Vp, rtol=1e-3)]
is_ = [y for y in ys if y is not None and np.isclose(np.max(y), Vp / R, rtol=1e-3)]
assert vs and is_, "Plot v on one axis and i = v/R on the other."
assert all(a.get_ylabel() for a in axes[:2]), "Label both y axes with their units."
```

::: right
Right. With one axis the current, {R} times smaller, would be a flat line near zero. Two y axes let both waveforms fill the plot, and the labels say which scale belongs to which.
:::
:::

::: check
kind: python
given: k = 1..5 int; s = 2 | 5 | 10

## The starter makes 2000 noisy readings of a 5 V reference (noise {s} mV standard deviation). Plot their histogram with `plt.hist(x_mV, bins=40)`, where `x_mV` is each reading's error from 5 V in millivolts, and label the x axis with its unit and the y axis as a count.

```python starter
import numpy as np
import matplotlib.pyplot as plt
x = 5 + np.random.default_rng(k).normal(0, s / 1000, 2000)
plt.plot(x)
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
x = 5 + np.random.default_rng(k).normal(0, s / 1000, 2000)
x_mV = (x - 5) * 1000
plt.hist(x_mV, bins=40)
plt.xlabel('error (mV)')
plt.ylabel('count')
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
ax = plt.gca()
bars = ax.patches
assert len(bars) == 40, "Use plt.hist with bins=40."
assert sum(b.get_height() for b in bars) == 2000, "All 2000 readings should be in the histogram."
left = min(b.get_x() for b in bars)
right = max(b.get_x() + b.get_width() for b in bars)
assert -10 * s < left < 0 < right < 10 * s, "Plot the error in millivolts, (x - 5) * 1000, so the bars sit around zero."
assert ax.get_xlabel() and ax.get_ylabel(), "Label both axes."
```

::: right
Right. Plotted as errors in millivolts, the spread reads directly off the axis: most readings sit within about {s} mV either side of zero, and almost none beyond three times that.
:::
:::

::: check
kind: choice

## Two curves differ by about 1%. Plotted together on axes from 0 to 10 V, they look the same. What shows the difference best?

- [x] Plot their difference, or their ratio, on its own axis
- [ ] Use a log y axis
- [ ] Draw the lines thicker
- [ ] Plot more points

::: right
Right. A 1% difference is 0.1 V on a 10 V scale, too small to see. Plotting the difference itself scales the axis to the thing you care about.
:::

::: misses
- [2] On a log axis a 1% ratio is a constant tiny gap, still hard to see.
- [3] Thicker lines hide small differences even more.
- [4] More points make each curve smoother but don't separate them.
:::
:::

::: explain
## Why do engineers plot frequency responses with a log frequency axis?

::: model
Frequency responses span many decades, from hertz to megahertz, and on a linear axis everything below the top decade would be squeezed against the left edge. A log axis gives each decade the same width, so behavior at 10 Hz and at 1 MHz is equally visible. It also turns the power-law roll-offs of filters into straight lines whose slopes (like −20 dB per decade) can be read directly.
:::
:::

::: practice

::: check
kind: python
given: tau = 1 | 2 | 5 | 10 | 20

## Plot $e^{-t/\tau}$ for `t` from 0 to 10τ (`tau` = {tau} ms) on a log $y$ axis with `plt.semilogy`.

```python starter
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0, 10 * tau, 200)
plt.plot(t, np.exp(-t / tau))
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0, 10 * tau, 200)
plt.semilogy(t, np.exp(-t / tau))
plt.xlabel("t (ms)")
plt.ylabel("v / V0")
```

```python tests
import matplotlib.pyplot as plt
assert plt.gca().get_yscale() == "log", "Use plt.semilogy: an exponential decay is a straight line on a log y axis."
```
:::

::: check
kind: python
given: lim = 1.8 | 2.5 | 3.3 | 5 | 12

## Plot the readings in the starter and draw a dashed horizontal line at the limit `lim` = {lim} V with `plt.axhline`.

```python starter
import numpy as np
import matplotlib.pyplot as plt
v = lim * (0.9 + 0.15 * np.sin(np.linspace(0, 6, 60)))
plt.plot(v)
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
v = lim * (0.9 + 0.15 * np.sin(np.linspace(0, 6, 60)))
plt.plot(v)
plt.axhline(lim, linestyle="--")
plt.ylabel("v (V)")
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
flat = [l for l in plt.gca().get_lines() if len(set(np.round(np.asarray(l.get_ydata(), float), 9))) == 1 and abs(float(l.get_ydata()[0]) - lim) < 1e-9]
assert flat, "Add plt.axhline(lim, linestyle='--')."
```
:::
:::
