Spectrogram Plotting with Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to create a spectrogram plot using Matplotlib. A spectrogram is a visual representation of the spectrum of frequencies of a signal as it varies with time. Spectrograms are commonly used to analyze the frequency content of a signal over time, such as in speech recognition, music analysis, and audio signal processing. We will use Python and Matplotlib to create a spectrogram plot of a signal.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} matplotlib/line_plots -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} python/variables_data_types -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} python/numeric_types -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} python/type_conversion -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} python/for_loops -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} python/lists -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} python/tuples -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} python/importing_modules -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} python/standard_libraries -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} python/math_random -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} python/numerical_computing -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} python/data_visualization -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} python/build_in_functions -.-> lab-48950{{"`Spectrogram Plotting with Matplotlib`"}} end

Import Libraries

We will start by importing the necessary libraries: NumPy and Matplotlib.

import matplotlib.pyplot as plt
import numpy as np

Generate Signal

Next, we will generate a signal to plot. In this example, we will create a signal that is the sum of two sine waves with different frequencies, and some random noise.

## Fixing random state for reproducibility
np.random.seed(19680801)

dt = 0.0005
t = np.arange(0.0, 20.0, dt)
s1 = np.sin(2 * np.pi * 100 * t)
s2 = 2 * np.sin(2 * np.pi * 400 * t)

## create a transient "chirp"
s2[t <= 10] = s2[12 <= t] = 0

## add some noise into the mix
nse = 0.01 * np.random.random(size=len(t))

x = s1 + s2 + nse  ## the signal

Generate Spectrogram

Now we will generate a spectrogram plot of the signal. We will use the specgram method from Matplotlib's Axes class to generate the spectrogram. This method returns four objects: Pxx, freqs, bins, and im. Pxx is the periodogram, freqs is the frequency vector, bins is the centers of the time bins, and im is the AxesImage instance representing the data in the plot.

NFFT = 1024  ## the length of the windowing segments
Fs = int(1.0 / dt)  ## the sampling frequency

fig, (ax1, ax2) = plt.subplots(nrows=2)
ax1.plot(t, x)
Pxx, freqs, bins, im = ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)

Customize Plot

We can customize the plot by adding titles, axis labels, and color maps.

fig, (ax1, ax2) = plt.subplots(nrows=2)
ax1.set_title('Time Domain Signal')
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Amplitude')
ax1.plot(t, x)

ax2.set_title('Spectrogram')
ax2.set_xlabel('Time (s)')
ax2.set_ylabel('Frequency (Hz)')
im = ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900, cmap='viridis')
fig.colorbar(im[3], ax=ax2)

Display Plot

Finally, we will display the plot.

plt.show()

Summary

In this lab, we learned how to create a spectrogram plot using Matplotlib. We generated a signal and used the specgram method from Matplotlib's Axes class to generate the spectrogram plot. We also customized the plot by adding titles, axis labels, and color maps. Spectrograms are useful for analyzing the frequency content of a signal over time and are commonly used in speech recognition, music analysis, and audio signal processing.

Other Python Tutorials you may like