如何使用 `matplotlib.pyplot.specgram` 绘制频带

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

我可以这样绘制频谱图(在 Jupyter notebook 中):

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

plt.show()

但是,我只对 15-20 kHz 范围感兴趣。 我怎样才能只绘制这个范围?

我可以看到函数 returns image,所以也许我可以将图像转换为矩阵并从矩阵中取出适当的切片...?

我可以看到该函数接受 vminvmax 但这些似乎没有记录并且使用它们不会产生有效结果。

您可以像通常使用 set_ylim() and set_xlim() 一样修改轴的限制。在这种情况下

plt.ylim([15000, 20000])

应将您的图限制在 15-20 kHz 范围内。一个完整的例子来自 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()