How to plot magnitude spectrum in Matplotlib in Python?

The magnitude spectrum shows the amplitude of different frequency components in a signal. Matplotlib's magnitude_spectrum() method plots the magnitude spectrum using the Fourier transform to analyze frequency content.

Basic Magnitude Spectrum Plot

Let's create a signal with noise and plot its magnitude spectrum ?

import matplotlib.pyplot as plt
import numpy as np

# Set figure properties
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Set random seed for reproducibility
np.random.seed(0)

# Sampling parameters
dt = 0.01  # sampling interval
Fs = 1 / dt  # sampling frequency (100 Hz)
t = np.arange(0, 10, dt)  # time array

# Generate noise and signal
nse = np.random.randn(len(t))  # white noise
r = np.exp(-t / 0.05)  # exponential decay
cnse = np.convolve(nse, r) * dt  # colored noise
cnse = cnse[:len(t)]
s = 0.1 * np.sin(4 * np.pi * t) + cnse  # signal + noise

# Create plot
fig, axs = plt.subplots()
axs.set_title("Magnitude Spectrum")
axs.magnitude_spectrum(s, Fs=Fs, color='C1')

plt.show()
Magnitude Spectrum Frequency (Hz) Magnitude Peak at 2Hz 0 10 20 30 40 50

Parameters

The magnitude_spectrum() method accepts several key parameters ?

  • x − Input signal array
  • Fs − Sampling frequency (default: 2)
  • color − Line color
  • scale − 'default', 'linear', or 'dB'

Magnitude Spectrum with dB Scale

Using decibel scale provides better visualization for signals with large dynamic range ?

import matplotlib.pyplot as plt
import numpy as np

# Create a cleaner sinusoidal signal
t = np.linspace(0, 1, 1000)
signal = np.sin(2 * np.pi * 10 * t) + 0.5 * np.sin(2 * np.pi * 25 * t)

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6))

# Linear scale
ax1.magnitude_spectrum(signal, Fs=1000, scale='linear')
ax1.set_title("Linear Scale")

# dB scale  
ax2.magnitude_spectrum(signal, Fs=1000, scale='dB')
ax2.set_title("Decibel Scale")

plt.tight_layout()
plt.show()

Key Points

  • The magnitude spectrum shows frequency content without phase information
  • Higher sampling frequency Fs extends the frequency range
  • Use scale='dB' for signals with wide amplitude range
  • Peaks indicate dominant frequencies in the signal

Conclusion

The magnitude_spectrum() method provides an easy way to visualize frequency content of signals. Use appropriate scaling and sampling frequency for clear analysis of your signal's spectral characteristics.

Updated on: 2026-03-25T23:03:01+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements