How to Create an Effective Filter Plot in Python

Filter Plot Techniques for Signal Processing ProfessionalsFilter plots are a fundamental tool for signal processing professionals. They visually communicate how filters modify signals across frequency, phase, and time domains, and they guide design, debugging, and performance evaluation. This article covers practical techniques for generating, interpreting, and presenting filter plots used in professional signal-processing workflows, with examples and tips for common tools (MATLAB, Python). It assumes familiarity with basic filter concepts (FIR/IIR, frequency response, phase, group delay).


Why filter plots matter

Filter plots translate mathematical descriptions of systems into intuitive visual forms. They help you:

  • Verify that the filter meets specifications (passband ripple, stopband attenuation, cutoff frequency).
  • Detect undesirable behavior (resonances, instability, excessive phase distortion).
  • Compare candidate designs and choose trade-offs (latency vs. attenuation).
  • Communicate results to engineers with different expertise.

Key plot types used by professionals: magnitude (linear and dB), phase, unwrapped phase, group delay, impulse response, step response, pole-zero plots, and spectrograms for time-varying analysis.


Preparing signals and filters for plotting

Good plots start with correct scaling, frequency axes, and units.

  • Sampling frequency (Fs): Always label axes in Hz (or normalized frequency 0–π). If Fs is known, present plots in Hz for clarity.
  • Frequency resolution: Use enough frequency samples to reveal details. For sharp filters, increase FFT length or use analytic frequency response routines.
  • Windowing: When plotting frequency-domain estimates of measured data, apply appropriate windows (Hann, Blackman-Harris) to reduce spectral leakage.
  • Normalization: State whether magnitude is normalized (e.g., unity passband) and whether plots show linear amplitude or dB.

Practical rule: For publication or review, include units, gridlines, and a legend specifying key parameters (Fs, filter order, design method, pass/stop band edges).


Magnitude response: linear vs dB, scaling, and dynamic range

Magnitude plots show how amplitude varies with frequency.

  • dB scale is preferred when responses span several orders of magnitude because it makes ripples and attenuation easier to see. Use 20·log10(|H(f)|) for amplitude response.
  • Linear scale is useful for seeing small deviations near unity gain in passband.
  • Dynamic range: When using dB, set y-limits appropriately (e.g., −120 dB to +5 dB) to avoid compressing detail.
  • Use dual plots (top: dB, bottom: linear) when you need both global attenuation and passband flatness visible.

Example axes:

  • Frequency axis: 0 to Fs/2 (Hz) or 0 to π (rad/sample).
  • Magnitude axis (dB): typically −150 to +5 dB for high-dynamic-range filters.

Tip: Plot both the intended specification masks (passband/stopband edges and tolerances) and the measured/derived response for immediate pass/fail visual checks.


Phase response and unwrapping

Phase shows how filter shifts signal components in time.

  • Wrapped phase can be misleading because of 2π discontinuities. Use phase unwrapping to reveal true phase behavior versus frequency.
  • For linear-phase FIR filters, expect a straight-line phase: slope corresponds to constant group delay.
  • For IIR filters, phase can be nonlinear—inspect for rapid phase changes near resonances.

Always pair phase plots with group delay to translate frequency-dependent phase into timing effects on signals.


Group delay: quantifying dispersion

Group delay τg(f) = −dφ/dω measures how different frequency components are delayed.

  • Plot group delay in samples or seconds (τg_seconds = τg_samples / Fs).
  • For communications and audio, excessive or varying group delay in the passband can cause distortion; aim for flat group delay in critical bands.
  • Use numerical differentiation of unwrapped phase or analytic formulas for designed filters. Beware noise amplification when differentiating noisy phase estimates—smooth before differentiating if necessary.

Impulse and step responses: time-domain validation

Time-domain plots reveal causality, stability, transient behavior, and ringing.

  • Impulse response: Useful for verifying FIR length, IIR decay, and symmetry (linear-phase FIR).
  • Step response: Highlights overshoot, settling time, and DC behavior.
  • For real-time systems, include time axis in milliseconds or samples and annotate expected group delay.

Use both time- and frequency-domain plots together: a narrow frequency response (sharp cutoff) often implies long impulse response (high latency).


Pole-zero plots and stability analysis

Poles and zeros in the z-plane reveal filter behavior intuitively.

  • Poles near the unit circle cause resonant peaks in magnitude; zeros on the unit circle create nulls.
  • For causal, stable filters, poles must lie inside the unit circle.
  • Annotate unit circle and mark conjugate pairs; overlay frequency points (e.g., ω = 0, π/2, π) to connect z-plane structure to frequency response features.

Pole-zero plots are particularly useful when diagnosing unexpected spectral peaks or when designing IIR filters by pole placement.


Spectrograms and time-frequency visualization

When signals or filters are time-varying, use spectrograms or wavelet scalograms.

  • Short-time Fourier transform (STFT) spectrograms show how a filter (or filtered signal) behaves over time and frequency.
  • Choose window length and overlap to balance time vs. frequency resolution.
  • For nonstationary filters (adaptive filters), create waterfall plots of frequency response across adaptation steps.

Example use: visualizing transient filter behavior during parameter sweeps or adaptation.


Practical techniques: numerical methods and plotting tips

  • Use analytic frequency response functions when available (freqz in MATLAB/Python) rather than FFT of impulse, for accuracy.
  • For high-Q resonances or very narrow stopbands, evaluate H(e^{jω}) at densely sampled ω near the critical frequencies.
  • Smoothing: For noisy empirical spectra, use median or Savitzky–Golay smoothing carefully; document any smoothing applied.
  • Log-frequency axis: Useful for wideband responses (audio, RF). Use semilogx for magnitude vs. frequency, but keep linear frequency plots for filter design specs that are defined in linear frequency.
  • Annotate: mark cutoff frequencies, ripple bounds, attenuation points, group delay at key bands, and filter order/design method on the figure.

Common visualization pitfalls and how to avoid them

  • Misleading axis limits: Zoomed-in plots without context can hide out-of-band problems—include an inset or dual-scale view.
  • Forgetting sampling rate: Normalized frequency plots are fine for theory, but real-world designs need Hz labeling.
  • Using wrapped phase without unwrapping: leads to apparent sudden jumps misinterpreted as nonlinearity.
  • Color maps that distort perception: avoid rainbow colormaps for spectrograms; use perceptually uniform maps (viridis, magma).
  • Over-annotating: too many lines and labels make plots unreadable—prioritize the essential annotations.

Example workflows (MATLAB and Python snippets)

MATLAB (conceptual):

Fs = 48000; [b,a] = designfilt(...); % design or load filter [H,w] = freqz(b,a,4096,Fs); subplot(2,1,1); plot(w,20*log10(abs(H))); grid on; ylabel('Magnitude (dB)'); subplot(2,1,2); plot(w,unwrap(angle(H))); grid on; ylabel('Phase (rad)'); 

Python (conceptual, using scipy and matplotlib):

import numpy as np from scipy import signal import matplotlib.pyplot as plt fs = 48000 b, a = signal.iirfilter(4, [1000/(fs/2)], btype='low', ftype='butter') w, h = signal.freqz(b, a, worN=8192, fs=fs) plt.figure() plt.subplot(2,1,1) plt.semilogx(w, 20*np.log10(abs(h))) plt.grid(True) plt.ylabel('Magnitude (dB)') plt.subplot(2,1,2) plt.plot(w, np.unwrap(np.angle(h))) plt.grid(True) plt.ylabel('Phase (rad)') plt.xlabel('Frequency (Hz)') plt.show() 

Comparing filter designs: what to show

When comparing several designs, present a concise set of plots:

  • Overlaid magnitude (dB) with spec masks.
  • Group delay overlay (or bar chart of max deviation).
  • Impulse response lengths and peak amplitudes.
  • A table summarizing filter order, max passband ripple, min stopband attenuation, latency (samples), and computational cost.
Design Order Passband ripple Stopband attn Latency (samples) Complexity
FIR window 512 0.1 dB 80 dB 256 High
Equiripple FIR 200 0.01 dB 100 dB 100 Medium
Butterworth IIR 4 3 dB (edge) 40 dB Low Low

Communication and presentation best practices

  • Use consistent color schemes and line styles across related figures.
  • For reports, include both high-resolution figures and vector formats (PDF/SVG) for publication.
  • Caption figures with the key takeaway sentence (e.g., “Design A meets passband ripple but exceeds stopband attenuation spec at 18 kHz”).

Advanced topics and diagnostics

  • Sensitivity analysis: plot response variations for coefficient quantization (fixed-point implementation) to assess robustness.
  • Pole-zero migration: animate pole-zero movements when sweeping parameters (e.g., Q factor) to diagnose stability margins.
  • Multi-rate filters: plot responses across folded bands and include aliasing masks when decimating/interpolating.
  • Nonlinear phase equalization: show pre- and post-equalization group delay and transient improvements.

Conclusion

Effective filter plots combine correct numerical methods, careful scaling, and purposeful annotations to turn design math into actionable insights. By choosing the right plot types (magnitude, phase, group delay, impulse), labeling clearly, and avoiding common visualization pitfalls, signal-processing professionals can design, diagnose, and communicate filter behavior with confidence.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *