Plot the phase spectrum in Python using Matplotlib

Plot the phase spectrum in Python using Matplotlib

Plotting the phase spectrum of a signal provides insight into the phase relationship of its frequency components. You can use the phase_spectrum function provided by matplotlib to plot the phase spectrum of a signal.

Here's how to do it:

  • Install Necessary Libraries:

First, make sure you have the necessary libraries installed:

pip install numpy matplotlib 
  • Plot the Phase Spectrum:

Here's a basic example using a simple sinusoidal signal:

import numpy as np import matplotlib.pyplot as plt # Sample signal: sum of two sinusoids fs = 500 # Sampling rate (in Hz) t = np.arange(0, 1.0, 1.0/fs) # Time vector f1, f2 = 5, 50 # Frequencies x = np.sin(2*np.pi*f1*t) + np.sin(2*np.pi*f2*t) # Plot the signal plt.figure(figsize=(12, 6)) plt.subplot(2, 1, 1) plt.plot(t, x) plt.title('Sample Signal') plt.xlabel('Time [s]') plt.ylabel('Amplitude') # Plot the phase spectrum plt.subplot(2, 1, 2) plt.phase_spectrum(x, Fs=fs) plt.title('Phase Spectrum') plt.xlabel('Frequency [Hz]') plt.ylabel('Phase [radians]') plt.tight_layout() plt.show() 

In this example:

  • We've created a signal x that's a sum of two sinusoids with frequencies f1 and f2.
  • We plot the time-domain representation of the signal in the first subplot.
  • In the second subplot, we plot the phase spectrum using plt.phase_spectrum(). The Fs argument is the sampling rate.

The resulting plot will show both the time-domain signal and its phase spectrum. Adjust the parameters as needed for your specific use case.


More Tags

whatsapp gridsearchcv iis-express file-io vba xml-serialization taxonomy-terms random-seed chmod multiple-instances

More Programming Guides

Other Guides

More Programming Examples