4

scipy.signal.spectrogram calculates the spectrogram for a signal, but I can't see an option to increase the frequency resolution of this spectrogram. Given the code available from the documentation, how could that be achieved?

from scipy import signal
import numpy as np
import matplotlib.pyplot as plt

fs = 10e3
N = 1e5
amp = 2 * np.sqrt(2)
noise_power = 0.01 * fs / 2
time = np.arange(N) / float(fs)
mod = 500*np.cos(2*np.pi*0.25*time)
carrier = amp * np.sin(2*np.pi*3e3*time + mod)
noise = np.random.normal(scale=np.sqrt(noise_power), size=time.shape)
noise *= np.exp(-time/5)
x = carrier + noise

f, t, Sxx = signal.spectrogram(x, fs)
plt.pcolormesh(t, f[0:10], Sxx[0:10,])
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.show()

1 Answer 1

16

The spectral resolution is determined by the number of points used in the FFT, which is controlled by the nperseg parameter. To increase the resolution you would increase the number of input points per FFT computation. For example, increasing the number of points from the default 256 to double the resolution (i.e. 512 points) you would call scipy.signal.spectrogram like so:

f, t, Sxx = signal.spectrogram(x, fs, nperseg=512)

Note that you could also use:

f, t, Sxx = signal.spectrogram(x, fs, nfft=512)

to use more points in the FFT, but not more input point per segment (i.e. zero padding each segment). This would essentially produce a spectrogram where the additional frequency points are interpolated. It wouldn't increase the resolution (i.e. two tones with very similar frequencies wouldn't be any more distinguishable), but the additional points would make the result appear more smooth.

1
  • 1
    Thanks for taking time to answer my question. Your explanation helped me to better understand the effects of the arguments of the function call. Feb 3, 2018 at 15:00

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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