TExcelTAD
Home › Signals, Systems & Digital Filters for Engineers › The Short-Time Fourier Transform and Spectrograms

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

frame 0 FFT 0 column frame 1 FFT 1 column frame 2 FFT 2 column frame 3 FFT 3 column frame 4 FFT 4 column Hann windows of nperseg samples, hop = nperseg - noverlap (here half a frame)

Take frames of LL samples (nperseg), multiply each by a window, FFT it, and advance by the hop H=L−noverlapH = L - \text{noverlap} samples:

X[m,k]=∑n=0L−1x[n+mH] w[n] e−j2πkn/LX[m, k] = \sum_{n=0}^{L-1} x[n + mH]\,w[n]\,e^{-j2\pi k n / L}

Frame mm is centred at time tm=(mH+L/2)/fst_m = (mH + L/2)/f_s; bin kk is at kfs/Lk f_s/L. The resolutions follow from the previous lessons:

Quantity Value Comment
frequency resolution ≈b fs/L\approx b\,f_s/L (b≈2b \approx 2 for Hann) longer frames: finer frequency
time resolution ≈L/fs\approx L/f_s (the frame duration) shorter frames: sharper time
time step between columns H/fsH/f_s overlap only makes the picture denser, not sharper

Their product is fixed: Δt⋅Δf≈b\Delta t \cdot \Delta f \approx b. 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 LL for a sweep. For a linear chirp whose frequency changes at α\alpha Hz per second, a frame of duration TLT_L sees the frequency move by αTL\alpha T_L, while its resolution is about 1/TL1/T_L. The two are equal, which gives the sharpest ridge, when

TL≈1αT_L \approx \frac{1}{\sqrt{\alpha}}

Worked example: a run-up with a short burst

Given: a sweep from 100 Hz100\ \text{Hz} to 2 kHz2\ \text{kHz} in 2 s2\ \text{s} (α=950 Hz/s\alpha = 950\ \text{Hz/s}), sampled at fs=8 kSa/sf_s = 8\ \text{kSa/s}, plus a 3 kHz3\ \text{kHz} burst lasting 0.1 s0.1\ \text{s} from t=1.2 st = 1.2\ \text{s}.

Find: a good frame length; the bin spacing, frame duration and time step for nperseg=256 with 50 %50\,\% overlap; the ridge frequency at 0.50.5, 1.01.0 and 1.5 s1.5\ \text{s}; how well the burst onset is located with 256- and 2048-sample frames.

Solve: TL≈1/950=32.4 msT_L \approx 1/\sqrt{950} = 32.4\ \text{ms}, i.e. L≈260L \approx 260 samples, so 256 is a good choice: bin spacing 8000/256=31.25 Hz8000/256 = 31.25\ \text{Hz}, frame duration 32 ms32\ \text{ms}, hop 128 samples =16 ms= 16\ \text{ms}. The ridge should follow f(t)=100+950tf(t) = 100 + 950t: 575575, 10501050 and 1525 Hz1525\ \text{Hz}. The burst onset can be located to within about one frame (32 ms32\ \text{ms}) with L=256L = 256, but only to within about 256 ms256\ \text{ms} with L=2048L = 2048.

Check:

python · try it yourself
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 11 Hz11\ \text{Hz} of the sweep, less than one 31.25 Hz31.25\ \text{Hz} bin, and the burst is found from 1.2001.200 to 1.296 s1.296\ \text{s}, 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 243 Hz243\ \text{Hz} of sweep smeared over about 60 bins, there is only one column every 128 ms128\ \text{ms}, and the 0.1 s0.1\ \text{s} burst shows up in a single column labelled 1.280 s1.280\ \text{s}: its timing is known only to about a frame, 256 ms256\ \text{ms}. Fine bins did not buy information here, because the signal does not stay put for 256 ms256\ \text{ms}.

Drawing the picture

python · try it yourself
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 50 %50\,\% overlap so no part of the signal is ignored (the overlapped periodic Hann windows then sum to a constant, the COLA condition; signal.istft inverts 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 100 Hz100\ \text{Hz} to 2 kHz2\ \text{kHz} in 2 s2\ \text{s} and record it with a sound card at 48 kSa/s48\ \text{kSa/s}. The best frame is about 32 ms32\ \text{ms}, i.e. L≈1536L \approx 1536 samples at 48 kSa/s48\ \text{kSa/s} (use 1024 or 2048).

Simulation. Change fs to 48 00048\,000 in the first program and compare L = 1024, 20482048 and 81928192.

What you would measure. A straight ridge from 100 Hz100\ \text{Hz} to 2 kHz2\ \text{kHz}; its slope gives the sweep rate to within about 1 %1\,\% 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 1 V1\ \text{V} 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

  1. fs=44.1 kSa/sf_s = 44.1\ \text{kSa/s}, nperseg=1024, noverlap=768. What are the bin spacing, frame duration and time step?
  2. A sweep changes at 10 kHz/s10\ \text{kHz/s}. What frame duration gives the sharpest ridge?
  3. Two harmonics 20 Hz20\ \text{Hz} apart must be separated with a Hann window. What minimum frame duration is needed?
Answer
  1. 43.07 Hz43.07\ \text{Hz}; 23.2 ms23.2\ \text{ms}; hop 256 samples =5.8 ms= 5.8\ \text{ms}.
  2. TL≈1/10 000=10 msT_L \approx 1/\sqrt{10\,000} = 10\ \text{ms}.
  3. About 2/20 Hz=100 ms2/20\ \text{Hz} = 100\ \text{ms}.

Test yourself

Making STFT frames longer

  1. improves both time and frequency resolution
  2. improves frequency resolution and worsens time resolution
  3. improves time resolution
  4. has no effect

Increasing the overlap from 50 % to 90 %

  1. sharpens the time resolution
  2. adds more columns without changing the resolution
  3. improves frequency resolution
  4. removes leakage

For a linear sweep at 950 Hz/s, the frame duration that gives the sharpest ridge is about

  1. 1 ms
  2. 32 ms
  3. 250 ms
  4. 1 s

With fs=8f_s = 8 kSa/s and nperseg=256, the bin spacing is

  1. 8 Hz
  2. 31.25 Hz
  3. 62.5 Hz
  4. 256 Hz