The Short-Time Fourier Transform and Spectrograms
A motor run-up, a bird call, a radar chirp, a bearing that clicks once per revolution, a switch-mode supply whose frequency hops with load: their spectra change with time, and a single FFT of the whole record averages everything into one blurred picture that says which frequencies occurred but not when. The short-time Fourier transform (STFT) cuts the signal into short overlapping frames and transforms each one; drawn as an image (time across, frequency up, level as colour) it is the spectrogram, the most used picture in audio, vibration and radio engineering. Its single design parameter, the frame length, trades time detail against frequency detail, and this lesson shows how to choose it. The mathematical side is in STFT and Spectrogram.
How the STFT works
Take frames of samples (nperseg), multiply each by a window, FFT it, and advance by the hop samples:
Frame is centred at time ; bin is at . The resolutions follow from the previous lessons:
| Quantity | Value | Comment |
|---|---|---|
| frequency resolution | ( for Hann) | longer frames: finer frequency |
| time resolution | (the frame duration) | shorter frames: sharper time |
| time step between columns | overlap only makes the picture denser, not sharper |
Their product is fixed: . This is the uncertainty principle in engineering form. Short frames (wideband spectrogram) show sharp clicks and onsets but smear tones vertically; long frames (narrowband spectrogram) resolve close harmonics but smear events horizontally.
Choosing for a sweep. For a linear chirp whose frequency changes at Hz per second, a frame of duration sees the frequency move by , while its resolution is about . The two are equal, which gives the sharpest ridge, when
Worked example: a run-up with a short burst
Given: a sweep from to in (), sampled at , plus a burst lasting from .
Find: a good frame length; the bin spacing, frame duration and time step for nperseg=256 with overlap; the ridge frequency at , and ; how well the burst onset is located with 256- and 2048-sample frames.
Solve: , i.e. samples, so 256 is a good choice: bin spacing , frame duration , hop 128 samples . The ridge should follow : , and . The burst onset can be located to within about one frame () with , but only to within about with .
Check:
import numpy as np
from scipy import signal
fs = 8000
t = np.arange(int(2.0 * fs)) / fs
x = signal.chirp(t, f0=100, t1=2.0, f1=2000, method="linear")
burst = (t >= 1.2) & (t < 1.3)
x = x + 0.5 * burst * np.sin(2 * np.pi * 3000 * t)
for L in (256, 2048):
f, tt, S = signal.spectrogram(x, fs, window="hann", nperseg=L, noverlap=L // 2)
print(f"L = {L}: bin {f[1]:.2f} Hz, frame {1e3 * L / fs:.0f} ms, step {1e3 * (tt[1] - tt[0]):.0f} ms, {len(tt)} columns")
for tq in (0.5, 1.0, 1.5):
m = np.argmin(abs(tt - tq))
low = f < 2500 # look for the sweep below the burst
print(f" t = {tt[m]:.3f} s: ridge at {f[low][np.argmax(S[low, m])]:7.2f} Hz (true {100 + 950 * tt[m]:7.2f} Hz)")
k3 = np.argmin(abs(f - 3000))
on = tt[S[k3] > 0.1 * S[k3].max()]
print(f" 3 kHz burst visible from {on.min():.3f} s to {on.max():.3f} s (true 1.200 to 1.300 s)")L = 256: bin 31.25 Hz, frame 32 ms, step 16 ms, 124 columns
t = 0.496 s: ridge at 562.50 Hz (true 571.20 Hz)
t = 0.992 s: ridge at 1031.25 Hz (true 1042.40 Hz)
t = 1.504 s: ridge at 1531.25 Hz (true 1528.80 Hz)
3 kHz burst visible from 1.200 s to 1.296 s (true 1.200 to 1.300 s)
L = 2048: bin 3.91 Hz, frame 256 ms, step 128 ms, 14 columns
t = 0.512 s: ridge at 585.94 Hz (true 586.40 Hz)
t = 1.024 s: ridge at 1074.22 Hz (true 1072.80 Hz)
t = 1.536 s: ridge at 1558.59 Hz (true 1559.20 Hz)
3 kHz burst visible from 1.280 s to 1.280 s (true 1.200 to 1.300 s)
With short frames the ridge peak is within about of the sweep, less than one bin, and the burst is found from to , one hop of the truth. With long frames the peak frequencies are, surprisingly, even closer: a linear sweep is symmetric about the frame centre, so the centre frequency wins. But each column now holds of sweep smeared over about 60 bins, there is only one column every , and the burst shows up in a single column labelled : its timing is known only to about a frame, . Fine bins did not buy information here, because the signal does not stay put for .
Drawing the picture
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
fs = 8000
t = np.arange(int(2.0 * fs)) / fs
x = signal.chirp(t, f0=100, t1=2.0, f1=2000) + 0.5 * ((t >= 1.2) & (t < 1.3)) * np.sin(2 * np.pi * 3000 * t)
fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True)
for ax, L in zip(axes, (256, 2048)):
f, tt, S = signal.spectrogram(x, fs, nperseg=L, noverlap=L // 2)
ax.pcolormesh(tt, f, 10 * np.log10(S + 1e-12), vmin=-80, vmax=-20, shading="auto")
ax.set_title(f"nperseg = {L} ({1e3 * L / fs:.0f} ms)")
ax.set_xlabel("t (s)")
axes[0].set_ylabel("f (Hz)")
plt.tight_layout(); plt.show()
print("colour scale: -80 to -20 dB re 1 V^2/Hz")colour scale: -80 to -20 dB re 1 V^2/Hz
The left panel (short frames) shows a thin ridge and a crisp burst; the right (long frames) shows a fat staircase and a burst that is smeared horizontally.
Practical choices
- Window: Hann for most work; frames tapered to zero need at least overlap so no part of the signal is ignored (the overlapped periodic Hann windows then sum to a constant, the COLA condition;
signal.istftinverts the STFT under the weaker NOLA condition). - Scaling:
scaling='density'(default) for noise-like signals,'spectrum'for tones; plot in dB with a fixed colour range, so pictures compare. - Real time: a spectrogram display is just the STFT computed block by block, one column per hop; the latency is at least one frame (Real-Time DSP).
- Beyond the STFT: wavelets and multi-resolution transforms use long windows at low frequencies and short ones at high frequencies; they are outside this course.
Guided lab: a sweep from a generator
Hand calculation. Set a function generator to a linear sweep from to in and record it with a sound card at . The best frame is about , i.e. samples at (use 1024 or 2048).
Simulation. Change fs to in the first program and compare L = 1024, and .
What you would measure. A straight ridge from to ; its slope gives the sweep rate to within about if you fit the ridge peaks over the whole sweep. Generator sweeps are often stepped rather than continuous; with short frames you may see the steps. The flyback at the end of each sweep shows as a vertical line (a broadband click).
Hazards and safe setup. Generator amplitude below the sound card's line-input range (about peak); never connect the generator to a microphone input with phantom power on.
Pitfalls
- Expecting more overlap to improve resolution (it only adds columns).
- Comparing spectrograms drawn with different colour scales or scalings.
- Choosing a frame length without asking how fast the signal changes.
- Forgetting that each column is labelled at the frame's centre, so events appear up to half a frame early or late.
Practice
- ,
nperseg=1024,noverlap=768. What are the bin spacing, frame duration and time step? - A sweep changes at . What frame duration gives the sharpest ridge?
- Two harmonics apart must be separated with a Hann window. What minimum frame duration is needed?
Answer
- ; ; hop 256 samples .
- .
- About .
Test yourself
Making STFT frames longer
- improves both time and frequency resolution
- improves frequency resolution and worsens time resolution
- improves time resolution
- has no effect
Increasing the overlap from 50 % to 90 %
- sharpens the time resolution
- adds more columns without changing the resolution
- improves frequency resolution
- removes leakage
For a linear sweep at 950 Hz/s, the frame duration that gives the sharpest ridge is about
- 1 ms
- 32 ms
- 250 ms
- 1 s
With kSa/s and nperseg=256, the bin spacing is
- 8 Hz
- 31.25 Hz
- 62.5 Hz
- 256 Hz