Matplotlib Frequency Spectrum Analysis Functions
Matplotlib Reference Documentation
Matplotlib provides plotting functions related to spectrum analysis and signal processing, commonly used in scientific computing and engineering visualization.
Function Overview
| Function | Description |
|---|---|
| acorr() | Plot auto-correlation graph |
| xcorr() | Plot cross-correlation graph |
| psd() | Plot power spectral density |
| csd() | Plot cross spectral density |
| specgram() | Plot spectrogram/time-frequency graph |
| cohere() | Plot coherence |
| angle_spectrum() | Plot angle spectrum |
| magnitude_spectrum() | Plot magnitude spectrum |
| phase_spectrum() | Plot phase spectrum |
Function Definitions
acorr() / xcorr()
matplotlib.pyplot.acorr(x, *, detrend=<function detrend_none>,
maxlags=10, **kwargs)
matplotlib.pyplot.xcorr(x, y, *, detrend=<function detrend_none>,
maxlags=10, normed=True, **kwargs)
psd() / csd()
matplotlib.pyplot.psd(x, NFFT=None, Fs=None, Fc=None,
detrend=None, window=None, noverlap=None, pad_to=None,
sides=None, scale_by_freq=None, **kwargs)
matplotlib.pyplot.csd(x, y, NFFT=None, Fs=None, Fc=None,
detrend=None, window=None, noverlap=None, pad_to=None,
sides=None, scale_by_freq=None, **kwargs)
specgram()
matplotlib.pyplot.specgram(x, NFFT=None, Fs=None, Fc=None,
detrend=None, window=None, noverlap=None, cmap=None,
xextent=None, pad_to=None, sides=None, scale_by_freq=None,
mode=None, scale=None, vmin=None, vmax=None, **kwargs)
angle_spectrum() / magnitude_spectrum() / phase_spectrum()
matplotlib.pyplot.angle_spectrum(x, Fs=None, Fc=None, **kwargs) matplotlib.pyplot.magnitude_spectrum(x, Fs=None, Fc=None, **kwargs) matplotlib.pyplot.phase_spectrum(x, Fs=None, Fc=None, **kwargs)
| Common Parameters | Description |
|---|---|
| Fs | Sampling frequency (Hz), default 2 |
| NFFT | Number of FFT points, affects frequency resolution |
| noverlap | Number of overlapping points in the window |
| window | Window function, default is hanning window |
| detrend | Detrending method: 'none', 'mean', 'linear' |
Usage Examples
Example 1: Auto-correlation and Cross-correlation
Example
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
t = np.linspace(0, 10, 500)
# Sine wave with noise
sig = np.sin(2 * np.pi * 2 * t) + np.random.randn(500) * 0.3
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4),
layout='constrained')
# Auto-correlation
ax1.acorr(sig, maxlags=100, color='steelblue')
ax1.set_title('acorr() - Auto-correlation of sin(4πt) + noise')
ax1.set_xlabel('Lag')
# Cross-correlation (signal and its delayed version)
delayed = np.roll(sig, 20)
ax2.xcorr(sig, delayed, maxlags=100, color='coral')
ax2.set_title('xcorr() - Cross-correlation (lag=20)')
ax2.set_xlabel('Lag')
plt.show()
import numpy as np
np.random.seed(42)
t = np.linspace(0, 10, 500)
# Sine wave with noise
sig = np.sin(2 * np.pi * 2 * t) + np.random.randn(500) * 0.3
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4),
layout='constrained')
# Auto-correlation
ax1.acorr(sig, maxlags=100, color='steelblue')
ax1.set_title('acorr() - Auto-correlation of sin(4πt) + noise')
ax1.set_xlabel('Lag')
# Cross-correlation (signal and its delayed version)
delayed = np.roll(sig, 20)
ax2.xcorr(sig, delayed, maxlags=100, color='coral')
ax2.set_title('xcorr() - Cross-correlation (lag=20)')
ax2.set_xlabel('Lag')
plt.show()
Example 2: Power Spectral Density
Example
import matplotlib.pyplot as plt
import numpy as np
# Generate a signal with a sampling rate of 100Hz (10Hz + 25Hz sine waves)
Fs = 100 # Sampling rate
t = np.arange(0, 5, 1/Fs)
sig = np.sin(2*np.pi*10*t) + 0.5*np.sin(2*np.pi*25*t)
+ np.random.randn(len(t))*0.5
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4),
layout='constrained')
# PSD
ax1.psd(sig, NFFT=256, Fs=Fs, color='steelblue')
ax1.set_title('psd() - Power Spectral Density')
# Spectrogram
ax2.specgram(sig, NFFT=128, Fs=Fs, noverlap=64,
cmap='viridis')
ax2.set_title('specgram() - Spectrogram')
ax2.set_xlabel('Time (s)')
ax2.set_ylabel('Frequency (Hz)')
plt.show()
import numpy as np
# Generate a signal with a sampling rate of 100Hz (10Hz + 25Hz sine waves)
Fs = 100 # Sampling rate
t = np.arange(0, 5, 1/Fs)
sig = np.sin(2*np.pi*10*t) + 0.5*np.sin(2*np.pi*25*t)
+ np.random.randn(len(t))*0.5
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4),
layout='constrained')
# PSD
ax1.psd(sig, NFFT=256, Fs=Fs, color='steelblue')
ax1.set_title('psd() - Power Spectral Density')
# Spectrogram
ax2.specgram(sig, NFFT=128, Fs=Fs, noverlap=64,
cmap='viridis')
ax2.set_title('specgram() - Spectrogram')
ax2.set_xlabel('Time (s)')
ax2.set_ylabel('Frequency (Hz)')
plt.show()
Example 3: Amplitude Spectrum and Phase Spectrum
Example
import matplotlib.pyplot as plt
import numpy as np
Fs = 200
t = np.arange(0, 2, 1/Fs)
sig = np.sin(2*np.pi*20*t) + 0.5*np.sin(2*np.pi*50*t)
fig, axes = plt.subplots(2, 2, figsize=(10, 8),
layout='constrained')
# Original signal
axes[0, 0].plot(t[:100], sig[:100])
axes[0, 0].set_title('Original Signal')
axes[0, 0].set_xlabel('Time (s)')
# Magnitude spectrum
axes[0, 1].magnitude_spectrum(sig, Fs=Fs, color='steelblue')
axes[0, 1].set_title('magnitude_spectrum()')
# Angle spectrum
axes[1, 0].angle_spectrum(sig, Fs=Fs, color='coral')
axes[1, 0].set_title('angle_spectrum()')
# Phase spectrum
axes[1, 1].phase_spectrum(sig, Fs=Fs, color='green')
axes[1, 1].set_title('phase_spectrum()')
plt.show()
print("example: spectrum analysis displayed")
import numpy as np
Fs = 200
t = np.arange(0, 2, 1/Fs)
sig = np.sin(2*np.pi*20*t) + 0.5*np.sin(2*np.pi*50*t)
fig, axes = plt.subplots(2, 2, figsize=(10, 8),
layout='constrained')
# Original signal
axes[0, 0].plot(t[:100], sig[:100])
axes[0, 0].set_title('Original Signal')
axes[0, 0].set_xlabel('Time (s)')
# Magnitude spectrum
axes[0, 1].magnitude_spectrum(sig, Fs=Fs, color='steelblue')
axes[0, 1].set_title('magnitude_spectrum()')
# Angle spectrum
axes[1, 0].angle_spectrum(sig, Fs=Fs, color='coral')
axes[1, 0].set_title('angle_spectrum()')
# Phase spectrum
axes[1, 1].phase_spectrum(sig, Fs=Fs, color='green')
axes[1, 1].set_title('phase_spectrum()')
plt.show()
print("example: spectrum analysis displayed")
Other Extensions