1

My aim is to plot the PSD of a complex vector x. I calculated the spectrum estimation using scipy.welch (version 1.4.1):

f, Px = scipy.signal.welch(**x**, return_onesided=False, detrend=False)

and then plotted:

plt.plot(f, 10*np.log10(Px),'.-')
plt.show()

The PSD was plotted fine, but I noticed an interpolation line from the last sample to the first on the plot. I then checked the frequency indices and noticed that they are ordered from DC(0) to half the sample rate(0.5 in this case) and then from -0.5 to almost zero. This is why the plot has a straight line across from Px(0.5) to Px(-0.5).

Why the returned f vector(and the appropriate Px) is not from -0.5 to 0.5 ? Can someone suggest a straight forward method? (I'm used to MATLAB and it is much simpler to plot a PSD there...) Thanks

Idnv
  • 13
  • 5

1 Answers1

1

Think about angles a complex value moves between two samples, it can be from 0 to 360 (this is the order that welch will return), but another way to see for say 200 degrees is that it is a 360-200=160 degrees to the other direction.

Since you are asking ti to bring the two sided spectrum

import numpy as np
import scipy.signal
import matplotlib.pyplot as plt
x = np.random.randn(1000)
x = x + np.roll(x, 1) + np.roll(x, -1) # rolling mean
f, p = scipy.signal.welch(x, detrend=False, return_onesided=False)

It will give you the positive frequency followed by the negative frequency spectrum. Numpy provides a fftshift function to rearrange a fft frequency vector. Check what the frequency (the x axis looks like)

plt.plot(f)
plt.plot(np.fft.fftshift(f))
plt.legend(['welch return', 'fftshifted'])

enter image description here

So if you plot directly you will see the line connecting the last point of the positive frequency spectrum to the first point of the negative frequency spectrum

plt.plot(f, np.log(p))

If you reorder both f and p you see the expected result

plt.plot(np.fft.fftshift(f), np.fft.fftshift(p))

enter image description here

Note that, for real data welch will return the same values for the negative part and the positive part.

Bob
  • 13,867
  • 1
  • 5
  • 27