A4 · Lesson 33 · Plots that communicate
Log axes, subplots and a Bode plot from scratch
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 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.
Name it
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 , linear : Bode plots |
plt.semilogy(...) | linear , log : 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 to , 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.
Worked example
Plot an RC low-pass's Bode plot, magnitude and phase, with the corner marked.
Show the solution
- Compute the transfer function on a log grid.
np.absandnp.anglework on complex arrays, so the transfer function is one line. - Plot magnitude and phase on shared axes. Two
semilogxsubplots, 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.
Worked example
Show a capacitor's and an inductor's impedance against frequency on one plot.
Show the solution
- Compute both impedances.
- 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()
- Read the lines. On log-log axes both are straight lines, slopes −1 and +1.
- Find the crossing. They cross at the resonant frequency:
Answer a loglog plot shows two straight lines, slopes −1 and +1, that cross at 15.9 kHz.
Check
Plot an RC low-pass's gain in dB, , against f on a log frequency axis, with fc = 1000 Hz. Label the axes with units.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
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 = 500 Hz. Label each axis.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
On log-log axes, plot the impedance sizes of a C = 10 nF capacitor and an L = 1 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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
On one figure, plot a voltage V on the left y axis and the current through R = 22 Ω 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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
The starter makes 2000 noisy readings of a 5 V reference (noise 2 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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Two curves differ by about 1%. Plotted together on axes from 0 to 10 V, they look the same. What shows the difference best?
Explain why
Why do engineers plot frequency responses with a log frequency axis?
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
Keep practicing
7 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.