简体   繁体   English

python 中绘制的功率谱的 y 值存在问题

[英]Problem with the y-values of the power spectrum plotted in python

I have got some data and I used MATLAB to plot the power spectrum.我有一些数据,我使用 MATLAB 到 plot 功率谱。 But I struggled to translate the same instructions to Python and obtain the exact plot.但我努力将相同的指令翻译成 Python 并获得准确的 plot。 The shape of the plot obtained in Python seems to be fine except that the y-values are positive for some reason?, Can anyone please tell me where I went wrong.在 Python 中获得的 plot 的形状似乎很好,除了 y 值由于某种原因是正的吗?谁能告诉我哪里出错了。 Below, I have attached the instructions in MATLAB and python along with the two plots obtained.下面,我附上了 MATLAB 和 python 中的说明以及获得的两个图。

MATLAB:                                                    
N=length(signal);
xdft = fft(signal);
xdft = xdft(1:N/2+1);
psdx=(1/(fs*N))*abs(xdft).^2;
psdx(2:end-1) = 2*psdx(2:end-1);
freq = 0:fs/N:fs/2;
plot(freq, 10*log10(psdx))

Python:
N = len(signal)
psdx = pow(np.fft.rfft(signal),2)
psdx[1:len(psdx)-1] = 2*psdx[1:len(psdx)-1]
f = np.arrange(0, (fs/2) + (1/N), fs/N)
plt.plot(f, (10*np.log10(psdx)))
plt.show() 

Signal can be found using: https://gofile.io/d/tlJm7F/edit Note that you need to load/read the file first可以使用以下命令找到信号: https://gofile.io/d/tlJm7F/edit请注意,您需要先加载/读取文件

在此处输入图像描述

在此处输入图像描述

from a quick glance, I think you are not dividing psdx by fs*N from your matlab code.快速浏览一下,我认为您没有将 matlab 代码中的 psdx 除以 fs*N。 That could be the reason.这可能是原因。 I would print values of psdx in matlab and check if it matches with the python.我会在 matlab 中打印 psdx 的值,并检查它是否与 python 匹配。

I just used MATLAB code as it is without using numpy.fft.rfft function.我只是使用了 MATLAB 代码,没有使用 numpy.fft.rfft function。 Also fs I assumed to be equal to 120. Please change as your code wants it to be.我还假设 fs 等于 120。请按照您的代码要求进行更改。

The plot looks like below, which to me is closer to your MATLAB code. plot 如下所示,对我来说更接近您的 MATLAB 代码。 根据 MATLAB 代码更改了 Python 代码

The code is here.代码在这里。

import matplotlib.pyplot as plt
import numpy as np
with open("./FileName2.txt","r") as FileHandle:
    Signal = FileHandle.readlines()
signal = np.array([i.rstrip("\n") for i in Signal])
fs = 120
N = len(signal)
xdft = np.fft.fft(signal)
xdft = xdft[:int(N/2)+1]
psdx=(1/(fs*N))*np.abs(xdft)**2
f = np.arange(0, (fs/2) + (1/N), fs/N)
plt.plot(f, (10*np.log10(psdx)))
plt.show() 

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

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