Skip to content

MATLAB - Plot Spectrogram

Visualizing Signals with Spectrograms in MATLAB

Section titled “Visualizing Signals with Spectrograms in MATLAB”

A spectrogram is a powerful tool for visualizing the frequency content of a signal as it changes over time. It’s essential in fields like audio processing, communications, and vibration analysis. MATLAB’s Signal Processing Toolbox™ provides the spectrogram function to easily compute and display these insightful plots.

A spectrogram is a 3D plot displayed as a 2D image. It shows:

  • Time on the x-axis.
  • Frequency on the y-axis.
  • Signal Power/Magnitude as the color intensity at each time-frequency point.

It’s generated by computing the Short-Time Fourier Transform (STFT), which involves breaking the signal into small, overlapping time windows and calculating the Fourier transform for each window.

The primary syntax for generating and plotting a spectrogram is:

spectrogram(x, window, noverlap, nfft, fs, 'yaxis')

Let’s break down the key parameters:

  • x: Your input signal vector.
  • window: A vector defining the windowing function (e.g., hamming(256)). This shapes the signal segments to reduce spectral leakage. The window length determines the trade-off between time and frequency resolution.
  • noverlap: The number of samples that overlap between consecutive windows. A typical value is 50% of the window length, which ensures smooth transitions.
  • nfft: The number of points for the Fast Fourier Transform (FFT). A larger nfft provides finer frequency resolution.
  • fs: The sampling frequency of the signal. This is crucial for correctly labeling the frequency axis in Hertz.
  • 'yaxis': An optional argument that plots the spectrogram directly with time on the x-axis and frequency on the y-axis.

Key Concept: The Time-Frequency Trade-off

  • A short window provides good time resolution (you can pinpoint when a frequency event occurs) but poor frequency resolution (it’s hard to distinguish between two close frequencies).
  • A long window provides good frequency resolution but poor time resolution.

A chirp signal is perfect for demonstrating a spectrogram because its frequency changes over time. Let’s create a signal that sweeps from 100 Hz to 400 Hz.

% --- Signal Parameters ---
samplingFreq = 1000; % Hz
duration = 2; % seconds
timeVector = 0:1/samplingFreq:duration-1/samplingFreq;
% --- Create a linear chirp signal ---
initialFreq = 100; % Hz
finalFreq = 400; % Hz
chirpSignal = chirp(timeVector, initialFreq, duration, finalFreq, 'linear');
% --- Spectrogram Parameters ---
windowLength = 256; % samples
overlap = round(0.5 * windowLength); % 50% overlap
nfft = 512; % FFT points
% --- Generate and Plot Spectrogram ---
figure;
spectrogram(chirpSignal, hamming(windowLength), overlap, nfft, samplingFreq, 'yaxis');
title('Spectrogram of a Linear Chirp Signal');
% Add a colorbar to show power levels
colorbar;

The resulting plot will clearly show a diagonal line, starting at 100 Hz at t=0 and rising to 400 Hz at t=2, visually confirming the signal’s changing frequency content.

Now, let’s analyze a signal composed of two distinct sine waves, one of which appears only for a short duration.

samplingFreq = 1000; % Hz
timeVector = 0:1/samplingFreq:2-1/samplingFreq;
% A 50 Hz sine wave present for the whole duration
sine1 = sin(2 * pi * 50 * timeVector);
% A 200 Hz sine wave present only from t=0.5s to t=1.5s
sine2 = sin(2 * pi * 200 * timeVector);
sine2(timeVector < 0.5 | timeVector > 1.5) = 0; % Gating the signal
combinedSignal = sine1 + sine2;
% --- Generate and Plot Spectrogram ---
figure;
spectrogram(combinedSignal, 128, 120, 128, samplingFreq, 'yaxis');
title('Spectrogram of a Gated Sinusoid');
colorbar;

The spectrogram for this example will show two horizontal lines. One line will be at 50 Hz, spanning the entire 2-second duration. The second, brighter line will appear at 200 Hz, but only between the 0.5 and 1.5-second marks, demonstrating the spectrogram’s ability to localize signals in both time and frequency.

  • Error: Undefined function 'spectrogram': This means the Signal Processing Toolbox™ is not installed or not active. You can install it from the Add-Ons menu.
  • Plot looks ‘smeared’ or ‘blocky’: Your time-frequency resolution is not well-matched to your signal. Experiment with the windowLength. A shorter window improves time resolution (less smearing); a longer window improves frequency resolution (less blockiness in frequency).
  • Frequency axis is incorrect: You likely forgot to provide the correct sampling frequency fs as an argument to the spectrogram function. Without it, the y-axis will be in normalized frequency.
  • Interactive Analysis: For interactive exploration, use pspectrum(signal, fs, 'spectrogram'). This creates a plot where you can zoom, pan, and measure peaks without regenerating the spectrogram.