Skip to main content
 首页 » 编程设计

python之用 matplotlib specgram 绘图

2025年05月04日14Terrylee

我正在尝试使用 matplotlib 绘制信号和信号的频谱图,但是...我仅获得信号的第一个值(样本)的频谱图(例如 30000 中的 60...)。

这是一个很长的文件,这就是为什么我只想绘制前 30000 个样本。

代码如下:

import matplotlib.pyplot as plt 
import numpy as np 
import pandas as pd 
 
Data=pd.read_csv('MySignal.txt',  
    skiprows=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],  
    header=0) 
print(Data.head()) 
DataI=Data['Sig'].tolist() 
print(len(Data.index)) 
DataI=DataI[0:30000] 
 
NFFT = 200     # the length of the windowing segments 
Fs = 500  # the sampling rate 
 
# plot signal and spectrogram 
 
t=range(len(DataI)) 
ax1 = plt.subplot(211) 
plt.plot(t, DataI) 
plt.subplot(212, sharex=ax1) 
Pxx, freqs, bins, im = plt.specgram(DataI, NFFT=NFFT,  
                        Fs=Fs,noverlap=100, cmap=plt.cm.gist_heat) 
plt.show()  

我不太了解plt.specgram是如何工作的,所以我不明白问题出在哪里......

非常感谢!

请您参考如下方法:

这里是一个快速而肮脏的合成示例,三个音调每个相隔一个 Octave ,效果很好。请阅读采样定理以了解频谱图的概念。实际上最好先学习如何通过使用 FFT 来绘制频谱(频谱图的垂直切片)。

import matplotlib.pyplot as plt 
import numpy as np 
import pandas as pd 
 
time1 = np.arange(0,5,0.0001) 
time = np.arange(0,15,0.0001) 
data1=np.sin(2*np.pi*300*time1) 
data2=np.sin(2*np.pi*600*time1) 
data3=np.sin(2*np.pi*900*time1) 
data=np.append(data1,data2 ) 
data=np.append(data,data3) 
print len(time) 
print len(data) 
 
NFFT = 200     # the length of the windowing segments 
Fs = 500  # the sampling rate 
 
# plot signal and spectrogram 
 
ax1 = plt.subplot(211) 
plt.plot(time,data)   # for this one has to either undersample or zoom in  
plt.xlim([0,15]) 
plt.subplot(212 )  # don't share the axis 
Pxx, freqs, bins, im = plt.specgram(data, NFFT=NFFT,   Fs=Fs,noverlap=100, cmap=plt.cm.gist_heat) 
plt.show()  

顶部的 x 轴以秒为单位。为了清楚起见,我在 5 秒内放大了 300 Hz 到 600 Hz 的过渡。底轴不是秒出来的,这也是我把轴的分享拿出来的原因。这可以修复(细节)。