简体   繁体   English

如何使用np.fft.fft制作PSD图?

[英]How to make a PSD plot using `np.fft.fft`?

I want to make a plot of power spectral density versus frequency for a signal using the numpy.fft.fft function. 我想使用numpy.fft.fft函数numpy.fft.fft信号的功率谱密度与频率的numpy.fft.fft I want to do this so that I can preserve the complex information in the transform and know what I'm doing, as apposed to relying on higher-level functions provided by numpy (like the periodogram function). 我想这样做,以便我可以保留转换中的复杂信息并知道我在做什么,因为这依赖于numpy提供的更高级别的函数(如periodogram函数)。 I'm following Mathwork's nice page about doing PSD analysis using Matlab's fft function: https://www.mathworks.com/help/matlab/ref/fft.html 我关注Mathwork关于使用Matlab的fft函数进行PSD分析的漂亮页面: https : //www.mathworks.com/help/matlab/ref/fft.html

In this example, I expect the PSD to peak at the frequency I used to construct the signal, which was 100 in this case. 在此示例中,我希望PSD在用于构造信号的频率处达到峰值,在本例中为100。 I generate the signal using 1000 time points a frequency of 100 inverse time units. 我使用1000个时间点生成信号,频率为100个逆时间单位。 I thought that the fft magnitude could be plotted against [0, nt/2] and the peaks would show up where there is the most energy in the frequency. 我认为可以将fft幅度相对于[0, nt/2]作图[0, nt/2]并且峰值将显示在频率中能量最大的位置。 When I did this, things went wrong. 当我这样做时,出现了问题。 I expected my PSD to peak at 100. 我期望我的PSD达到100的峰值。

How can I make a spectral density plot of frequency vs energy contained in that frequency using np.fft.fft ? 如何使用np.fft.fft绘制频率与该频率中包含的能量的频谱密度图?

Edit 编辑

to clarify, in my real problem, I only know that my characteristic frequency is much larger than my sample frequency 为了澄清我的实际问题,我只知道我的特征频率比我的采样频率大得多

import matplotlib.pyplot as plt
import numpy as np
t = np.arange(1000)
sp = np.fft.fft(np.sin(100 * t * np.pi))
trange = np.linspace(0, t[-1] / 2, t.size)
plt.plot(trange, np.abs(sp) / t.size)
plt.show()

在此处输入图片说明

This is a sketch I made of the expected output: 这是我对预期输出的草图:

在此处输入图片说明

What is your sample frequency? 您的采样频率是多少? This sequence you are generating can represent a infinite number of continuous time signals according to the sample frequency. 根据采样频率,您生成的此序列可以表示无限数量的连续时间信号。 The sample frequency needs to be at least twice the maximum signal frequency, as stated by the Sampling Theorem, so, using fs = 250Hz and using a sine of 10 seconds it becomes: 如采样定理所述,采样频率至少应为最大信号频率的两倍,因此,使用fs = 250Hz并使用10秒的正弦值将变为:

import matplotlib.pyplot as plt
import numpy as np

fs = 250
t = np.arange(0, 10, 1/fs)
sp = np.fft.fft(np.sin(2*np.pi * 100 * t))
trange = np.linspace(0, fs, len(t))
plt.plot(trange, np.abs(sp))
plt.show()

If you run this you will see a peak at 100Hz as expected. 如果执行此操作,您将看到预期的100Hz峰值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM