The PSD is a common plot in the field of signal processing. NumPy has
many useful libraries for computing a PSD. Below we demo a few examples
of how this can be accomplished and visualized with Matplotlib.
Below we'll show a slightly more complex example that demonstrates
how padding affects the resulting PSD.
dt=np.pi/100.fs=1./dtt=np.arange(0,8,dt)y=10.*np.sin(2*np.pi*4*t)+5.*np.sin(2*np.pi*4.25*t)y=y+np.random.randn(*t.shape)# Plot the raw time seriesfig,axs=plt.subplot_mosaic([['signal','signal','signal'],['zero padding','block size','overlap'],],layout='constrained')axs['signal'].plot(t,y)axs['signal'].set_xlabel('Time (s)')axs['signal'].set_ylabel('Signal')# Plot the PSD with different amounts of zero padding. This uses the entire# time series at onceaxs['zero padding'].psd(y,NFFT=len(t),pad_to=len(t),Fs=fs)axs['zero padding'].psd(y,NFFT=len(t),pad_to=len(t)*2,Fs=fs)axs['zero padding'].psd(y,NFFT=len(t),pad_to=len(t)*4,Fs=fs)# Plot the PSD with different block sizes, Zero pad to the length of the# original data sequence.axs['block size'].psd(y,NFFT=len(t),pad_to=len(t),Fs=fs)axs['block size'].psd(y,NFFT=len(t)//2,pad_to=len(t),Fs=fs)axs['block size'].psd(y,NFFT=len(t)//4,pad_to=len(t),Fs=fs)axs['block size'].set_ylabel('')# Plot the PSD with different amounts of overlap between blocksaxs['overlap'].psd(y,NFFT=len(t)//2,pad_to=len(t),noverlap=0,Fs=fs)axs['overlap'].psd(y,NFFT=len(t)//2,pad_to=len(t),noverlap=int(0.025*len(t)),Fs=fs)axs['overlap'].psd(y,NFFT=len(t)//2,pad_to=len(t),noverlap=int(0.1*len(t)),Fs=fs)axs['overlap'].set_ylabel('')axs['overlap'].set_title('overlap')fortitle,axinaxs.items():iftitle=='signal':continueax.set_title(title)ax.sharex(axs['zero padding'])ax.sharey(axs['zero padding'])plt.show()
This is a ported version of a MATLAB example from the signal
processing toolbox that showed some difference at one time between
Matplotlib's and MATLAB's scaling of the PSD.
This is a ported version of a MATLAB example from the signal
processing toolbox that showed some difference at one time between
Matplotlib's and MATLAB's scaling of the PSD.
It uses a complex signal so we can see that complex PSD's work properly.