P i
P i

Reputation: 30684

How to plot frequency band using `matplotlib.pyplot.specgram`

I can plot a spectrogram (in a Jupyter notebook) thus:

fs = 48000
noverlap = (fftFrameSamps*3) // 4
spectrum2d, freqs, timePoints, image = \
    plt.specgram( wav, NFFT=fftFrameSamps, Fs=fs, noverlap=noverlap )

plt.show()

enter image description here

However, I am only interested in the 15-20 kHz range. How can I plot only this range?

I can see that the function returns image, so maybe I could convert the image to a matrix and take an appropriate slice from the matrix...?

I can see that the function accepts vmin and vmax but these appear to be undocumented and playing with them doesn't yield a valid result.

Upvotes: 1

Views: 1455

Answers (1)

William Miller
William Miller

Reputation: 10320

You can modify the limits of the axis as you would normally with set_ylim() and set_xlim(). In this case

plt.ylim([15000, 20000])

should restrict your plot to the 15-20 kHz range. For a complete example drawing from the Spectrogram Demo:

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(19680801)

dt = 0.0005
t = np.arange(0.0, 20.0, dt)
s1 = np.sin(2 * np.pi * 100 * t)
s2 = 2 * np.sin(2 * np.pi * 400 * t)

# create a transient "chirp"
s2[t <= 10] = s2[12 <= t] = 0

# add some noise into the mix
nse = 0.01 * np.random.random(size=len(t))

x = s1 + s2 + nse  # the signal
NFFT = 1024  # the length of the windowing segments
Fs = int(1.0 / dt)  # the sampling frequency

fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(14, 7))
ax1.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
ax2.set_ylim([50, 500])
plt.show()

enter image description here

Upvotes: 2

Related Questions