1
$\begingroup$

I want to do time-frequency analysis of a signal. So i decided to use spectrogram function from scipy. This function returns, three parameters f,t,Sxx. I am using below arguements:

  • x : my signal

  • fs : 1000 Hz

  • window : hann, with size = 300

  • nperseg : 300, same as window size

  • noverlap : 25

My question is about returned time segments of this function.

As far as I understand the first time segment for which we calculate fft must be 300 samples, then subtract 25 from it calculate fft for next window of 300 samples,and so on. So the signal of length 1s must be divided in 4 time segments. .275,.500,.775,1. , but the function returns :

f,t,Sxx=spectrogram(sig1,fs=1000,window=get_window('hann',300),noverlap=25,scaling='spectrum',nperseg=300) t Out[172]: array([ 0.15 , 0.425, 0.7 ])

can someone please suggest if I am thinking wrong or there is a bug in spectrogram function.

$\endgroup$
1
$\begingroup$

As the returned value shows, the first spectrum is computed at time $t=0.15$ s. With a sampling rate of 1000 Hz, that means that the first analysis window is centred at sample $n=150$. So the first analysis frame spans the samples $n \in [0,300[$.

Because your overlap is set to 25 samples, the second analysis frame spans the samples $n \in [275,575[$, thus overlapping in its first 25 samples with the first analysis frame. The second analysis frame is then centred at time $t=0.425$ s or in samples $n=425$.

The third analysis frame again overlaps 25 samples with the second one. Thus, it spans the samples $n \in [550,850[$ and is centred at time $t=0.7$ s or in samples $n=700$.

The next analysis frame would span the samples $n \in [825,1125]$ and is not computed because it would go over the range of samples in the input signal.

$\endgroup$
  • $\begingroup$ Thank you hulappa, that makes sense, but lets say I have a signal of 1s length with fs=1000 Hz, and I want to find 150 Hz of frequencies, so I was thinking to take a window size of 300, samples, and overlap=25, so that I can resolve 150 Hz, can you please suggest what window size and overlap I should use, so that I can get 4 time segments in 1s and test for 150 Hz in my signal. $\endgroup$ – Gagandeep Singh Jan 18 '18 at 20:39
  • $\begingroup$ Lets say I can take 1125 samples from the signal, then I will get 4 time segments with proper frequency resolution(150 Hz), but when i plot the spectrogram with matplotlib.pyplot, it only goes till 0.975. How can I plot for full 1s. For example I am getting this. I used this code to plot it: plt.pcolormesh(t, f, Sxx,cmap='PiYG') $\endgroup$ – Gagandeep Singh Jan 18 '18 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.