Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to plot a phase spectrum in Matplotlib in Python?
A phase spectrum shows the phase relationship of different frequency components in a signal. In Matplotlib, you can plot a phase spectrum using the phase_spectrum() method to visualize how phase varies with frequency.
Basic Phase Spectrum Plot
Here's how to create a phase spectrum with a synthetic signal containing sine waves and noise ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Set random seed for reproducible results
np.random.seed(0)
# Sampling parameters
dt = 0.01 # sampling interval
Fs = 1 / dt # sampling frequency
t = np.arange(0, 10, dt)
# Generate noise
nse = np.random.randn(len(t))
r = np.exp(-t / 0.05)
cnse = np.convolve(nse, r) * dt
cnse = cnse[:len(t)]
# Create signal with sine wave and noise
s = 0.1 * np.sin(4 * np.pi * t) + cnse
# Create phase spectrum plot
fig, axs = plt.subplots()
axs.set_title("Phase Spectrum")
axs.phase_spectrum(s, Fs=Fs, color='C2')
plt.show()
Understanding the Components
The phase spectrum reveals important signal characteristics ?
- Sampling frequency (Fs) ? Determines the frequency range displayed
- Signal composition ? Shows phase relationships at different frequencies
- Noise effects ? Random phase variations from noise components
- Color parameter ? Customizes the plot appearance
Comparing Multiple Signals
You can plot multiple phase spectra to compare different signals ?
import matplotlib.pyplot as plt
import numpy as np
# Create two different signals
t = np.linspace(0, 1, 1000)
signal1 = np.sin(2 * np.pi * 10 * t) # 10 Hz sine wave
signal2 = np.sin(2 * np.pi * 10 * t + np.pi/4) # Same frequency, different phase
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
# Plot phase spectra
ax1.phase_spectrum(signal1, Fs=1000, color='blue')
ax1.set_title('Signal 1: Phase = 0')
ax2.phase_spectrum(signal2, Fs=1000, color='red')
ax2.set_title('Signal 2: Phase = ?/4')
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
Fs |
Sampling frequency | Fs=1000 |
color |
Line color | color='C2' |
window |
Windowing function | window='hann' |
Conclusion
Phase spectrum plots help analyze the phase relationships in signals using phase_spectrum(). They're essential for signal processing applications where phase information is critical for understanding signal behavior.
Advertisements
