首页 > 解决方案 > 如何使用“matplotlib.pyplot.specgram”绘制频带

问题描述

我可以绘制一个频谱图(在 Jupyter 笔记本中),因此:

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

plt.show()

在此处输入图像描述

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

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

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

标签: pythonmatplotlibspectrogram

解决方案


您可以像通常使用set_ylim()和一样修改轴的限制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()

在此处输入图像描述


推荐阅读