用matplotlib谱图进行绘图? [英] Plotting with matplotlib specgram?

查看:71
本文介绍了用matplotlib谱图进行绘图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to plot a signal and the spectrogram of the signal with matplotlib, but... i get the spectrogram only for the first value (samples) of my signal (like 60 of the 30000...).

这是一个非常长的文件,这就是为什么我只想绘制前30000个样本的原因.

It's a very long file, that's why I would like to plot only the first 30000 sample.

这是代码:

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 是如何工作的,所以我不明白问题出在哪里......

I don't understand well how plt.specgram work, so i don't understand where is the problem...

非常感谢!

推荐答案

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

Here a quick and dirty synthetic example of three tones an octave apart each, which works fine. Please read up on the sampling theorem to understand the idea of a spectrogram. It's actually best to first learn how to plot spectra (vertical slices of the spectrogram) by just playing with FFTs.

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的过渡处进行了放大.底部轴不是以秒为单位,这就是为什么我取出了这些轴的原因.这可以修复(细节).

The top x-axis is in seconds.I zoomed in at the transition of 300 Hz to 600 Hz at 5 seconds for clarity. The bottom axis is not in seconds, which is why I took out the sharing of the axes. That can be fixed (detail).

这篇关于用matplotlib谱图进行绘图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆