# Spectrogram from scipy.signal with Python

To test the python spectrogram (from scipy.signal) , I've created a signal with 2 harmonics: 2 Hz and 8 Hz. Then I've added 50Hz noise and a trend (https://i.sstatic.net/XePzK.png). I wanted to retrieve those frequencies with spectrogram. I only find 10 Hz and about 50 Hz with the noised signal (https://i.sstatic.net/adMtp.png). I tried on the original signal without trend and without noise. I only find about 10 Hz (https://i.sstatic.net/Dy7pG.png). Do you have any explanation of this ? The code is only 3 lines ("new_sa" is the noised signal with the trend and "PerEch" period of sampling).

from scipy.signal import spectrogram
f,t1,Sxx = spectrogram(new_sa,1/PerEch)
plt.pcolormesh(t1,f,Sxx)
plt.colorbar()


Thank you

• It would be useful if you put a self-contained code (i.e. with the generation of the signals you're using). Commented Aug 17, 2018 at 0:01
• Hello, here is my entire code: github.com/Cyalas/Ney/blob/master/Spectrogram%20-%20PYthon Commented Aug 17, 2018 at 7:38

You need to make sure to make sure you define your time axis and PerEch correctly.

from scipy.signal import spectrogram
import pylab as plt
import numpy as np
PerEch = 20
N = 512
time = np.arange(N) / float(PerEch)
new_sa = np.sin(2*np.pi*2*time)
new_sa += np.sin(2*np.pi*8*time)
new_sa += np.random.randn(N)
plt.plot(time,new_sa)
plt.show()
f,t1,Sxx = spectrogram(new_sa,PerEch)
plt.pcolormesh(t1,f,Sxx)
plt.colorbar()
plt.show()

• Hello, I don't think I've big difference with your code (github.com/Cyalas/Ney/blob/master/Spectrogram%20-%20PYthon) apart from the values Commented Aug 17, 2018 at 7:52
• The values are pretty important. Because you need to make sure the Nyquist rate is satisfied and also the way you assign time indices matters. I put the script there for you to check and cross-compare. Commented Aug 17, 2018 at 9:11

The input to your spectrogram is too short in terms of time. To get 2 Hz plot resolution, you need an input vector long enough to represent at least 0.5 seconds (preferably 3X more) worth of samples at your sample rate.