0
0
SciPydata~7 mins

Spectrogram generation in SciPy

Choose your learning style9 modes available
Introduction

A spectrogram shows how sound or signal frequencies change over time. It helps us see patterns in sounds or signals.

To analyze bird songs or animal sounds to see different notes.
To check machine sounds for unusual noises that mean problems.
To study speech patterns in language learning or speech therapy.
To visualize music notes and beats in a song.
To detect signals in scientific data like earthquakes or heartbeats.
Syntax
SciPy
from scipy.signal import spectrogram
frequencies, times, Sxx = spectrogram(signal, fs, window='hann', nperseg=256, noverlap=None)

signal is your input data, like a list or array of sound values.

fs is the sample rate, how many data points per second.

Examples
Basic spectrogram with default window and segment size.
SciPy
frequencies, times, Sxx = spectrogram(signal, fs=1000)
Using a Hamming window and larger segment size for smoother results.
SciPy
frequencies, times, Sxx = spectrogram(signal, fs=2000, window='hamming', nperseg=512)
Overlap segments by 128 points to get better time resolution.
SciPy
frequencies, times, Sxx = spectrogram(signal, fs=1000, noverlap=128)
Sample Program

This code creates a signal with two tones and shows their frequencies over time using a spectrogram plot.

SciPy
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: 50 Hz and 120 Hz
signal = 0.5 * np.sin(2 * np.pi * 50 * t) + 0.3 * np.sin(2 * np.pi * 120 * t)

# Generate spectrogram
frequencies, times, Sxx = spectrogram(signal, fs)

# Plot spectrogram
plt.pcolormesh(times, frequencies, Sxx, shading='gouraud')
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.title('Spectrogram Example')
plt.colorbar(label='Intensity')
plt.show()
OutputSuccess
Important Notes

The spectrogram output Sxx shows intensity of frequencies over time.

Choosing nperseg affects time and frequency detail: smaller means better time detail, larger means better frequency detail.

Use plt.pcolormesh to visualize the spectrogram nicely.

Summary

Spectrograms help us see how frequencies in a signal change over time.

Use scipy.signal.spectrogram with your signal and sample rate.

Visualize with a color plot to understand frequency intensity.