A spectrogram shows how sound or signal frequencies change over time. It helps us see patterns we can't hear or see directly.
0
0
Spectrogram visualization in Signal Processing
Introduction
To analyze bird songs or animal sounds to understand their patterns.
To check the quality of a recorded voice or music by seeing frequency changes.
To find hidden signals or noises in machine vibrations for maintenance.
To study speech patterns in language learning or speech therapy.
To visualize heartbeats or brain waves in medical tests.
Syntax
Signal Processing
import matplotlib.pyplot as plt from scipy.signal import spectrogram frequencies, times, Sxx = spectrogram(signal, fs) plt.pcolormesh(times, frequencies, 10 * np.log10(Sxx)) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.title('Spectrogram') plt.colorbar(label='Intensity [dB]') plt.show()
signal is your input data, like sound or vibration.
fs is the sampling rate, how many samples per second.
Examples
Basic spectrogram with a 1000 Hz sampling rate.
Signal Processing
frequencies, times, Sxx = spectrogram(signal, fs=1000)Specifies segment length to get better frequency resolution.
Signal Processing
frequencies, times, Sxx = spectrogram(signal, fs=2000, nperseg=256)
Uses smooth shading for nicer visualization.
Signal Processing
plt.pcolormesh(times, frequencies, 10 * np.log10(Sxx), shading='gouraud')
Sample Program
This code creates a signal that changes frequency after 1 second. The spectrogram shows this change clearly.
Signal Processing
import numpy as np import matplotlib.pyplot as plt from scipy.signal import spectrogram # Create a sample signal: 2 seconds, 1000 Hz sample rate fs = 1000 T = 2 t = np.linspace(0, T, T * fs, endpoint=False) # Signal with two frequencies changing over time signal = np.sin(2 * np.pi * 50 * t) * (t < 1) + np.sin(2 * np.pi * 120 * t) * (t >= 1) # Calculate spectrogram frequencies, times, Sxx = spectrogram(signal, fs) # Plot spectrogram plt.figure(figsize=(8, 4)) plt.pcolormesh(times, frequencies, 10 * np.log10(Sxx), shading='gouraud') plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.title('Spectrogram visualization of changing frequencies') plt.colorbar(label='Intensity [dB]') plt.tight_layout() plt.show()
OutputSuccess
Important Notes
Use 10 * np.log10(Sxx) to convert power to decibels for better visualization.
Adjust nperseg to balance time and frequency detail.
Shading='gouraud' makes the image smoother and easier to read.
Summary
Spectrograms show how frequencies in a signal change over time.
They help find patterns in sounds or vibrations you can't hear directly.
Use libraries like scipy.signal and matplotlib to create and display spectrograms easily.