python - matplotlib.mlab 和 numpy.abs(numpy.fft.fft(data)) 中可用的模量谱结果之间的差异

标签 python numpy matplotlib signal-processing fft

我有一个简单的正弦波。我正在尝试找到频域中的幅度谱。
我使用了函数matplotlib.mlab.magnitude_spectrum(data) 我想验证这个结果,所以我尝试了 numpy.abs(numpy.fft.fft(data)) 结果不同。
应该是一样的吧?即使我尝试
numpy.sqrt(matplotlib.mlab.psd(data)),结果不同。

我正在寻找对此的解释。

最佳答案

有两个主要区别。首先matplotlib.mlab.magnitude_spectrum在进行 FFT 之前对输入数据应用窗函数(默认情况下为 Hanning window )。其次,它仅返回正频率,而 np.fft.fft 同时返回正频率和负频率:

import numpy as np
from matplotlib import pyplot as plt


x = np.random.randn(500)

mag1, f = plt.mlab.magnitude_spectrum(x)

# apply a hanning window to x
xw = np.hanning(x.shape[0]) * x

# use np.fft.rfft to get the positive frequencies only
mag2 = np.abs(np.fft.rfft(xw))

fig, ax = plt.subplots(1, 1)
ax.hold(True)
ax.plot(f, mag1, '-k', lw=2)
ax.plot(f, mag2, '--r', lw=2)
plt.show()

enter image description here

matplotlib.mlab.psd做了一些更复杂的事情 - 它使用 Welch's method 计算周期图,而不仅仅是取 FFT 幅度的平方。它基本上采用信号的加窗重叠段的平均周期图,为您提供对噪声更鲁棒的“平滑”周期图,但会牺牲一些频率分辨率。根据您的信号的外观以及您对 psdNFFT=noverlap= 参数的选择,您应该期望结果看起来相当与 magnitude_spectrum 不同。

关于python - matplotlib.mlab 和 numpy.abs(numpy.fft.fft(data)) 中可用的模量谱结果之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29844783/

相关文章:

python - 使用 scipy 和 numpy 中的函数计算 z-score

python - Python中的对数刻度使y刻度消失

python - 将 matplotlib 图保存到内存并放置在 tkinter Canvas 上

python - 使用 matplotlib 自定义类似颜色条的绘图

python正则表达式获取字符串后的值

python - 如何从输入数据集中删除非数字列?

python - 你如何在 mxnet 中连接符号

python - 使用琶音处理空格或逗号分隔的标记列表

Python:将带有参数的函数传递给函数

python - bool numpy 数组的子矩阵求和