📖 Scenario: You have recorded a short audio signal and want to see how its frequency content changes over time. A spectrogram is a great way to visualize this. It shows frequencies on one axis, time on another, and the intensity of frequencies as colors.
🎯 Goal: Build a simple program that creates a spectrogram from a given audio signal and displays it as a color image.
📋 What You'll Learn
Create a sample audio signal as a numpy array
Set up parameters for the spectrogram calculation
Calculate the spectrogram using a signal processing function
Display the spectrogram using a plotting library
💡 Why This Matters
🌍 Real World
Spectrograms are used in audio analysis, speech recognition, and music visualization to understand how sound frequencies change over time.
💼 Career
Knowing how to create and interpret spectrograms is useful for roles in audio engineering, data science, and signal processing.
Progress0 / 4 steps
1
Create a sample audio signal
Create a numpy array called signal that contains a 1-second sine wave at 5 Hz sampled at 100 Hz. Use numpy's linspace to create time points and sin to generate the wave.
Signal Processing
Hint
Use np.linspace(0, 1, fs, endpoint=False) to create time points and np.sin(2 * np.pi * 5 * t) for the sine wave.
2
Set spectrogram parameters
Create a variable called nperseg and set it to 20. This will be the length of each segment for the spectrogram calculation.
Signal Processing
Hint
Set nperseg = 20 to define the segment length.
3
Calculate the spectrogram
Use scipy.signal.spectrogram to calculate the spectrogram of signal. Store the frequency array in frequencies, the time array in times, and the spectrogram matrix in Sxx. Use fs as the sampling frequency and nperseg as the segment length.
Signal Processing
Hint
Call spectrogram(signal, fs=fs, nperseg=nperseg) and unpack the result into frequencies, times, and Sxx.
4
Display the spectrogram
Use matplotlib.pyplot to display the spectrogram matrix Sxx as an image. Use plt.pcolormesh(times, frequencies, Sxx) to plot. Add labels for the x-axis as Time [sec] and y-axis as Frequency [Hz]. Finally, call plt.show() to display the plot.
Signal Processing
Hint
Use plt.pcolormesh(times, frequencies, Sxx) to plot, then label axes with plt.xlabel and plt.ylabel. Finally, call plt.show().
Practice
(1/5)
1. What does a spectrogram primarily show in signal processing?
easy
A. How signal frequencies change over time
B. The total energy of a signal
C. The raw amplitude values of a signal
D. The phase shift of a signal
Solution
Step 1: Understand spectrogram purpose
A spectrogram is a visual tool that shows frequency content of a signal as it changes over time.
Step 2: Compare options to definition
Only How signal frequencies change over time describes frequency changes over time, which matches the spectrogram's function.
Final Answer:
How signal frequencies change over time -> Option A
Quick Check:
Spectrogram = frequency over time [OK]
Hint: Spectrogram = frequency vs time graph [OK]
Common Mistakes:
Confusing spectrogram with waveform plot
Thinking it shows only amplitude
Mixing phase information with frequency
2. Which Python library is commonly used to create spectrograms?
easy
A. matplotlib
B. pandas
C. scikit-learn
D. numpy
Solution
Step 1: Identify libraries for plotting
matplotlib is widely used for plotting graphs including spectrograms.
Step 2: Check other libraries' main uses
pandas is for data frames, scikit-learn for machine learning, numpy for arrays but not direct plotting.
Final Answer:
matplotlib -> Option A
Quick Check:
Plotting spectrogram = matplotlib [OK]
Hint: Plotting graphs? Think matplotlib [OK]
Common Mistakes:
Choosing numpy for plotting directly
Confusing pandas with plotting library
Selecting scikit-learn which is for ML
3. Given this Python code snippet, what is the shape of the output spectrogram array?
import numpy as np
from scipy.signal import spectrogram
fs = 1280 # Sampling frequency
x = np.sin(2 * np.pi * 50 * np.linspace(0, 1, fs))
f, t, Sxx = spectrogram(x, fs)
print(Sxx.shape)
medium
A. (1000, 1000)
B. (129, 9)
C. (50, 1000)
D. (1000, 129)
Solution
Step 1: Understand spectrogram output dimensions
The spectrogram function returns frequency bins and time bins. For default parameters, frequency bins are nfft/2+1 (default nfft=256), so 129 frequency bins.
Step 2: Calculate time bins
With 1 second signal sampled at 1280 Hz and default windowing, time bins are 9 segments.
4. Identify the error in this code snippet for plotting a spectrogram:
import matplotlib.pyplot as plt
from scipy.signal import spectrogram
fs = 500
x = [1, 2, 3, 4, 5]
f, t, Sxx = spectrogram(x, fs)
plt.specgram(Sxx)
plt.show()
medium
A. Using plt.specgram instead of plt.plot
B. Missing import for numpy
C. Sampling frequency fs is too high
D. Passing Sxx instead of x to plt.specgram
Solution
Step 1: Understand spectrogram output and plotting
The spectrogram function returns frequencies, times, and the spectrogram matrix Sxx. plt.specgram expects raw signal, not Sxx.
Step 2: Identify misuse of plt.specgram
Passing Sxx (already spectrogram data) to plt.specgram causes error; should plot Sxx with plt.imshow or pass raw signal to plt.specgram.
Final Answer:
Passing Sxx instead of x to plt.specgram -> Option D
Quick Check:
Plot raw signal with plt.specgram, not spectrogram matrix [OK]
Hint: plt.specgram needs raw signal, not spectrogram data [OK]
Common Mistakes:
Passing spectrogram matrix to plt.specgram
Confusing plt.specgram with plt.imshow
Ignoring correct input types for plotting
5. You want a spectrogram with smoother frequency resolution but less time detail. Which parameter should you increase?
hard
A. Sampling frequency (fs)
B. Overlap between windows (noverlap)
C. Window size (nperseg)
D. FFT length (nfft) smaller than window size
Solution
Step 1: Understand window size effect on spectrogram
Larger window size increases frequency resolution but reduces time resolution (smoother frequency, less time detail).
Step 2: Evaluate other parameters
Increasing overlap smooths time axis but does not improve frequency resolution as much. Sampling frequency affects max frequency, not resolution. nfft smaller than window size is invalid.
Final Answer:
Window size (nperseg) -> Option C
Quick Check:
Increase window size for better frequency resolution [OK]
Hint: Bigger window = better frequency, worse time detail [OK]
Common Mistakes:
Increasing overlap to improve frequency resolution
Changing sampling frequency to affect resolution
Setting nfft smaller than window size
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.