Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Signal Processing

Spectrograms, Peaks and Resampling

Estimate power spectra with welch, track changing frequencies with spectrogram, detect peaks with prominence, resample, smooth with savgol_filter and find delays by cross-correlation.

A single FFT gives one spectrum for a whole recording. Real signals are messier: the spectrum of noisy data is itself noisy, a bird call or a vehicle changes pitch as time passes, and sometimes the interesting thing is not a frequency at all but the position of a heartbeat or a bump. This lesson collects the next tools in scipy.signal: welch for a stable power spectrum, spectrogram for frequency over time, find_peaks for locating events, resample for changing the sampling rate, savgol_filter and detrend for cleaning, and cross-correlation for measuring how much one signal lags another.

It continues from The Fast Fourier Transform and Filter Design and Filtering Signals.

flowchart TD
    S["long signal"] --> C["cut into overlapping segments"]
    C --> W["apply a window to each"]
    W --> F["FFT of each segment"]
    F --> A["average the spectra<br/>= welch (one stable spectrum)"]
    F --> K["keep them in time order<br/>= spectrogram (image: time x frequency)"]

Welch's method and the spectrogram start identically; one averages the segments, the other keeps them separate.

A stable spectrum with Welch's method

The raw FFT power of a noisy signal fluctuates wildly from bin to bin, and it does not become smoother with a longer recording; you just get more bins that are equally noisy. Welch's method fixes this by splitting the signal into overlapping segments, windowing and transforming each, and averaging the squared magnitudes. You trade frequency resolution for a much lower variance. signal.welch(x, fs, nperseg=...) returns frequencies and the power spectral density (PSD), in units of signal power per Hz. Shorter segments mean smoother but coarser spectra.

Python Periodogram versus Welch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The periodogram's noise floor scatters by roughly its own height, so peaks are hard to tell from noise. Welch's curve is far calmer, and the two tones stand out. Keep nperseg a power of two and long enough to separate the tones you care about (resolution is fs / nperseg).

Frequency over time: the spectrogram

When the frequency content changes, one spectrum is not enough. The spectrogram computes the spectrum of short consecutive segments and stacks them into an image: time on the horizontal axis, frequency on the vertical axis, colour for power. signal.spectrogram(x, fs, nperseg=...) returns f, t and the matrix Sxx. The segment length is a trade-off you cannot escape: long segments give sharp frequency detail but blur when things happen, short ones do the opposite.

signal.chirp makes a test signal whose frequency sweeps steadily, ideal for seeing this.

Python A rising chirp in a spectrogram

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The printed frequencies climb as time passes, and the image shows one bright diagonal line, which is the signature of a chirp. Use a decibel scale for the colours, because power values span many orders of magnitude.

Finding peaks

signal.find_peaks(x, ...) returns the indices of local maxima and a dictionary of properties. Almost every real signal has many tiny wiggles, so the filtering arguments are what make it useful:

  • height: minimum peak value (a number, or (min, max)).
  • distance: minimum number of samples between peaks; the taller one wins.
  • prominence: how far a peak stands out from its surroundings. Formally it is the vertical distance to the higher of the two surrounding valleys. It ignores the overall baseline, which makes it the most robust criterion.
  • width: minimum width measured at half the prominence.
Python Peaks with and without conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Without conditions the noise produces dozens of tiny "peaks". A modest prominence threshold keeps only the three real ones. Choose the threshold from the noise level: noise of standard deviation 0.05 never produces a prominence of 0.3, but a real bump does. For measurement beyond location, signal.peak_widths and signal.peak_prominences return those properties for given peak indices.

If your peaks sit in a noisy signal, smooth lightly first (next sections) or raise prominence. To find valleys, run find_peaks(-x).

Smoothing that keeps peaks: Savitzky-Golay

A moving average smooths noise but also flattens peaks. The Savitzky-Golay filter fits a low-degree polynomial to each sliding window and reports the polynomial's value at the centre. Because it follows curvature, it preserves peak height and width much better. signal.savgol_filter(x, window_length, polyorder) needs an odd window and polyorder < window_length. Passing deriv=1 returns a smooth derivative, handy for slopes of noisy data.

Python Savitzky-Golay against a moving average

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The moving average lowers the peak noticeably; Savitzky-Golay stays close to the true height. The derivative estimate is also far better than differencing the raw noisy samples, which amplifies the noise.

Detrending

Slow drifts (a sensor warming up, a baseline wandering) add a large low-frequency component that swamps the spectrum and leaks into every bin. signal.detrend(x) subtracts the best-fit straight line (type="linear", the default) or just the mean (type="constant"). Remove trends before an FFT or a Welch estimate.

Python Detrend before looking at the spectrum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

(welch detrends each segment by default, which is why the example switches that off to show the effect of doing it ourselves.)

Resampling

Changing the sampling rate is the everyday companion of filtering. Downsampling must remove frequencies above the new Nyquist limit first, or they alias. Two tools do this correctly:

  • signal.resample(x, num) works in the frequency domain; it assumes the signal is periodic, so it can ring at the edges for signals that are not.
  • signal.resample_poly(x, up, down) upsamples by up, applies an anti-aliasing FIR filter and downsamples by down; it is usually the better choice for non-periodic data and for ratios like 3/2. signal.decimate(x, q) is the shortcut for integer downsampling.

Plain slicing x[::q] does not filter and can alias badly.

Python Downsampling with and without anti-aliasing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The 400 Hz tone is beyond the new Nyquist limit of 125 Hz. Slicing folds it into the data as a false 100 Hz tone, while resample_poly removes it first.

Cross-correlation: how much does one signal lag another?

Slide one signal across another and measure the match at every offset: that is cross-correlation. The offset with the highest value is the delay that best aligns the signals. It is how sonar finds range, how microphones locate a sound source and how you synchronize two recordings. signal.correlate(a, b, mode="full") returns the values and signal.correlation_lags(len(a), len(b)) returns the matching offsets in samples. A positive best lag means the first signal is a delayed copy of the second.

Python Measuring a time delay

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For sub-sample accuracy you can interpolate around the correlation maximum, but whole-sample estimates are often enough. Normalize the signals (subtract the mean, divide by the standard deviation) first when amplitudes differ a lot.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does Welch's method give a smoother spectrum than a single periodogram?

    Averaging many segment spectra reduces the random scatter at the cost of coarser frequency resolution.
  2. 2. In a spectrogram, what is the trade-off controlled by nperseg?

    Longer segments resolve frequencies finely but blur timing; shorter segments locate events in time but blur frequency.
  3. 3. Which find_peaks argument measures how much a peak stands out from its surroundings, regardless of the baseline?

    Prominence is the vertical rise above the higher of the two neighbouring valleys, so it ignores the overall baseline level.
  4. 4. Why use resample_poly(x, 1, 4) instead of x[::4] to reduce the sampling rate fourfold?

    Slicing keeps every fourth sample unchanged, so frequencies above the new Nyquist limit alias. resample_poly filters them out first.
  5. 5. Cross-correlating a and b peaks at lag +50. What does that mean?

    With correlate(a, b), the best lag is the number of samples by which a lags b.

Summary

  • welch averages windowed segment spectra for a stable PSD; nperseg trades smoothness for resolution.
  • spectrogram shows frequency against time as an image; plot it on a decibel scale.
  • find_peaks with prominence, height, distance and width separates real peaks from noise; use -x for valleys.
  • savgol_filter smooths while preserving peak shapes and can return smooth derivatives; detrend removes drift before spectral analysis.
  • resample, resample_poly and decimate change the sampling rate with proper anti-aliasing; plain slicing does not.
  • correlate with correlation_lags measures the delay between two signals.

Next up: leave signals behind and meet data that is mostly zeros in Sparse Matrices.