pyQTGraph 设置轴值(FFT)

1 投票
1 回答
3284 浏览
提问于 2025-04-18 01:22

这是一个名为 FFT_Plot 的类:

def __init__(self,
             win,
             nSamples,
             aData,
             sRate,
             wFunction,
             zStart = 0):
    self.nSamples = nSamples    # Number of Sample must be a 2^n power
    self.aData = aData          # Amplitude data array
    self.sRate = sRate          # Sample Rate
    self.wFunction = wFunction  # Windowing Function
    self.zStart = zStart        # Start of Zoom Window if Used
    self.zStop = nSamples/2     # End of Zoom Window if Used
    # Instantiate a plot window within an existing pyQtGraph window.
    self.plot = win.addPlot(title="FFT")
    self.update(aData)
    self.grid_state()

    self.plot.setLabel('left', 'Amplitude', 'Volts')
    self.plot.setLabel('bottom', 'Frequency', 'Hz')

def update(self, aData):
    x = np.fft.fft(aData,)
    amplitude = np.absolute(x)
    fScale = np.linspace(0 , 50000, self.nSamples)
    self.plot.plot(amplitude)
    # Calculate and set-up X axis
    self.plot.setXRange(SampleSize/2, 0)

def grid_state(self, x = True, y = True):
    self.plot.showGrid(x, y)

我的问题其实很简单。我该怎么改变显示在 x 轴和 y 轴上的数值呢?

当我使用 2048 个样本并显示一半的样本(从 0 到样本的一半)时,显示的范围是从 0 到 1。如果我不能正确显示频率或幅度,那我计算这些又有什么用呢?

如果我改变范围,就相当于在放大频谱……我看过一些例子,但因为没有解释我就很快迷失了。

任何帮助都非常感谢……

正如 Luke 提到的……我之前没注意到我可以使用一个 'X' 数组。:) 下面是修正后的初学者类:

class FFT_Plot():

def __init__(self,
             win,
             nSamples,
             aData,
             sRate,
             wFunction,
             zStart = 0):
    self.nSamples = nSamples    # Number of Sample must be a 2^n power
    self.aData = aData          # Amplitude data array
    self.sRate = sRate          # Sample Rate as Frequency
    self.wFunction = wFunction  # Windowing Function
    self.zStart = zStart        # Start of Zoom Window if Used
    self.zStop = nSamples/2     # End of Zoom Window if Used
    # Instantiate a plot window within an existing pyQtGraph window.
    self.plot = win.addPlot(title="FFT")
    self.update(aData)
    self.grid_state()
    self.plot.setLabel('left', 'Amplitude', 'Volts')
    self.plot.setLabel('bottom', 'Frequency', 'Hz')

def update(self, aData):
    x = np.fft.fft(aData,)
    amplitude = np.absolute(x)
    # Create a linear scale based on the Sample Rate and Number of Samples.
    fScale = np.linspace(0 , self.sRate, self.nSamples)
    self.plot.plot(x = fScale, y = amplitude, pen={'color': (0, 0, 0), 'width': 2})
    # Because the X-axis is now tied to the fScale, which os based on sRate,
    # to set any range limits you must use the sRate.
    self.plot.setXRange(self.sRate/2, 0)

def grid_state(self, x = True, y = True):
    self.plot.showGrid(x, y)

任何数字信号处理(DSP)方面的人都可以随意添加非数学性的评论。

另外,似乎为了让 y 轴正确显示,幅度数组需要提前进行相应的缩放。

1 个回答

2

在pyqtgraph中,坐标轴的数值是根据显示的数据的坐标系统自动确定的。当你只提供y值调用plot()时,它会默认你想要的x值是整数,比如说range(len(yValues))。所以,如果你想让你的样本的x值范围从0到5万,你需要在调用plot时提供这些x值:self.plot.plot(x=fScale, y=amplitude)。你会发现坐标轴的数值会相应地变化。

撰写回答