TExcelTAD
Home › SciPy › SciPy Spectral Analysis

SciPy Spectral Analysis

A single FFT of a whole recording answers "which frequencies are present?". Two practical questions need more: How is the signal's power spread across frequencies, reliably, despite noise? and How does the frequency content change over time? scipy.signal provides Welch's method for the first and the spectrogram for the second.

Power spectral density

The power spectral density (PSD) shows how a signal's power is distributed over frequency. A raw FFT of a noisy signal gives a very jagged PSD (the periodogram). Welch's method splits the signal into overlapping segments, computes a windowed periodogram of each and averages them, trading frequency resolution for a much smoother, more reliable estimate:

python · try it yourself
import numpy as np
from scipy import signal

rng = np.random.default_rng(3)
fs = 1000
t = np.arange(0, 10, 1 / fs)
x = 0.5 * np.sin(2 * np.pi * 60 * t) + rng.normal(0, 1, t.size)

f_p, p_p = signal.periodogram(x, fs)
f_w, p_w = signal.welch(x, fs, nperseg=1024)

noise_p = p_p[(f_p > 100) & (f_p < 400)]
noise_w = p_w[(f_w > 100) & (f_w < 400)]
print(f"periodogram: {f_p.size} bins, noise floor spread (std/mean) = {noise_p.std() / noise_p.mean():.2f}")
print(f"welch      : {f_w.size} bins, noise floor spread (std/mean) = {noise_w.std() / noise_w.mean():.2f}")
print(f"welch peak at {f_w[np.argmax(p_w)]:.1f} Hz")
periodogram: 5001 bins, noise floor spread (std/mean) = 1.04
welch      : 513 bins, noise floor spread (std/mean) = 0.26
welch peak at 59.6 Hz

The Welch estimate has far fewer bins, but its noise floor is much flatter, so real peaks are easy to tell from random fluctuations.

Parameter Effect
nperseg samples per segment: larger = finer resolution, noisier estimate
noverlap overlap between segments (default: half a segment)
window taper applied to each segment (default "hann")
scaling "density" (power per Hz) or "spectrum" (power per bin)

Plotting a PSD

PSDs span many orders of magnitude, so they are plotted on a logarithmic axis:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

rng = np.random.default_rng(3)
fs = 1000
t = np.arange(0, 10, 1 / fs)
x = (0.5 * np.sin(2 * np.pi * 60 * t) + 0.3 * np.sin(2 * np.pi * 180 * t)
     + rng.normal(0, 1, t.size))

f, pxx = signal.welch(x, fs, nperseg=2048)
plt.semilogy(f, pxx)
plt.xlabel("frequency (Hz)")
plt.ylabel("PSD (V^2/Hz)")
plt.title("Welch power spectral density")
plt.show()

peaks, _ = signal.find_peaks(pxx, height=10 * np.median(pxx))   # 10x the noise floor
print("peaks found at:", np.round(f[peaks], 1), "Hz")
peaks found at: [ 60.1 180.2] Hz

Total power and band power

Integrating the PSD over a frequency range gives the power in that band. Over all frequencies it equals the signal's variance — a useful sanity check. Here we compare the power of brain-wave–like bands in a synthetic signal:

python · try it yourself
import numpy as np
from scipy import signal
from scipy.integrate import trapezoid

rng = np.random.default_rng(5)
fs = 256
t = np.arange(0, 30, 1 / fs)
x = (2.0 * np.sin(2 * np.pi * 10 * t)        # strong 10 Hz "alpha" rhythm
     + 0.7 * np.sin(2 * np.pi * 20 * t)      # weaker 20 Hz "beta"
     + rng.normal(0, 1, t.size))

f, pxx = signal.welch(x, fs, nperseg=4 * fs)
print(f"total power {trapezoid(pxx, x=f):.3f}  vs  variance {x.var():.3f}")

bands = {"theta 4-8": (4, 8), "alpha 8-13": (8, 13), "beta 13-30": (13, 30)}
for name, (lo, hi) in bands.items():
    sel = (f >= lo) & (f <= hi)
    print(f"{name:11}: {trapezoid(pxx[sel], x=f[sel]):.3f}")
total power 3.299  vs  variance 3.310
theta 4-8  : 0.030
alpha 8-13 : 2.072
beta 13-30 : 0.393

Spectrograms: frequency over time

When frequency changes over time — a siren, birdsong, an engine speeding up — one spectrum can't show it. A spectrogram computes a spectrum for each short time slice:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

fs = 2000
t = np.arange(0, 3, 1 / fs)
x = signal.chirp(t, f0=50, t1=3, f1=600, method="linear")   # rising tone

f, seg_t, Sxx = signal.spectrogram(x, fs, nperseg=256)
plt.pcolormesh(seg_t, f, 10 * np.log10(Sxx + 1e-12), shading="gouraud")
plt.xlabel("time (s)")
plt.ylabel("frequency (Hz)")
plt.title("Spectrogram of a chirp")
plt.show()

dominant = f[np.argmax(Sxx, axis=0)]
for i in [0, len(seg_t) // 2, len(seg_t) - 1]:
    print(f"t = {seg_t[i]:.2f} s: dominant frequency about {dominant[i]:.0f} Hz")
t = 0.06 s: dominant frequency about 62 Hz
t = 1.52 s: dominant frequency about 328 Hz
t = 2.86 s: dominant frequency about 578 Hz

The dominant frequency rises steadily from about 60 Hz near the start to nearly 600 Hz at the end, just as the chirp was designed (50 Hz to 600 Hz over 3 seconds).

Tip: Spectrograms have a built-in trade-off: short segments locate events precisely in time but blur frequency; long segments do the opposite. Try different nperseg values to see which view answers your question.

Test yourself

What does Welch's method do to get a smoother PSD estimate?

  1. Uses a longer FFT
  2. Averages windowed periodograms of overlapping segments
  3. Removes all noise
  4. Applies a low-pass filter first

What does integrating a PSD over all frequencies give you?

  1. The mean of the signal
  2. The total power, equal to the signal's variance
  3. The peak frequency
  4. The sampling rate

Which tool shows how a signal's frequency content changes over time?

  1. periodogram
  2. welch
  3. spectrogram
  4. rfftfreq