python - 我的 PyQt 图的 Y 轴是颠倒的(甚至是文本)?

标签 python plot real-time pyqtgraph

今天是我尝试使用 PyQtGraph 的第一天。到目前为止我真的很喜欢它,但我似乎无法完全理解事情是如何运作的..

我正在尝试将两个 FFT 绘图小部件放入同一窗口中。经过多次尝试和错误,我找到了我认为正确的方法。然而现在我有两个图显示了正确的信息,但 Y 轴上的所有内容都是倒置的。

此外,缩放和平移似乎也不正确(整个图移动,而不仅仅是其中的数据)。

此图显示了单个 GraphicsWindow 中的两个实时音频 fft 图。左边我使用 addPlot 和 addItem,右边我使用 addViewBox 和 addItem。 Upside Down Data

为了彻底,我尝试使用 item.invertY(True) 和 item.scale(1,-1)。 在这两种情况下,它都会反转 Y 轴数据,但不会反转文本或轴,也不会解决平移/缩放问题。

这个 Python 脚本是我能编写的所有内容。

它基于此文件:pyqtgraph live running spectrogram from microphone

import numpy as np
import pyqtgraph as pg
import pyaudio
from PyQt4 import QtCore, QtGui

FS = 44100 #Hz
CHUNKSZ = 1024 #samples

class MicrophoneRecorder():
    def __init__(self, signal):
        self.signal = signal
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(format=pyaudio.paInt16,
                            channels=1,
                            rate=FS,
                            input=True,
                            frames_per_buffer=CHUNKSZ)

    def read(self):
        data = self.stream.read(CHUNKSZ)
        y = np.fromstring(data, 'int16')
        self.signal.emit(y)

    def close(self):
        self.stream.stop_stream()
        self.stream.close()
        self.p.terminate()



class SpectrogramWidget2(pg.PlotWidget):

    read_collected = QtCore.pyqtSignal(np.ndarray)
    def __init__(self):
        super(SpectrogramWidget2, self).__init__()

        self.img = pg.ImageItem()
        self.addItem(self.img)

        self.img_array = np.zeros((1000, CHUNKSZ/2+1))

        # bipolar colormap
        pos = np.array([0., 0.5, 1.])
        color = np.array([[0,0,0,255], [0,255,0,255], [255,0,0,255]], dtype=np.ubyte)
        cmap = pg.ColorMap(pos, color)
        pg.colormap
        lut = cmap.getLookupTable(0.0, 1.0, 256)

        # set colormap
        self.img.setLookupTable(lut)
        self.img.setLevels([0,100])

        # setup the correct scaling for y-axis
        freq = np.arange((CHUNKSZ/2)+1)/(float(CHUNKSZ)/FS)
        yscale = 1.0/(self.img_array.shape[1]/freq[-1])

        self.img.scale((1./FS)*CHUNKSZ, yscale)

        self.setLabel('left', 'Frequency', units='Hz')

        # prepare window for later use
        self.win = np.hanning(CHUNKSZ)
        #self.show()

    def update(self, chunk):
        # normalized, windowed frequencies in data chunk
        spec = np.fft.rfft(chunk*self.win) / CHUNKSZ
        # get magnitude 
        psd = abs(spec)
        # convert to dB scaleaxis
        psd = 20 * np.log10(psd)

        # roll down one and replace leading edge with new data
        self.img_array = np.roll(self.img_array, -1, 0)
        self.img_array[-1:] = psd

        self.img.setImage(self.img_array, autoLevels=False)

class SpectrogramWidget(pg.PlotWidget):

    read_collected = QtCore.pyqtSignal(np.ndarray)
    def __init__(self):
        super(SpectrogramWidget, self).__init__()

        self.img = pg.ImageItem()
        self.addItem(self.img)

        self.img_array = np.zeros((1000, CHUNKSZ/2+1))

        # bipolar colormap
        pos = np.array([0., 0.5, 1.])
        color = np.array([[0,0,0,255], [0,255,0,255], [255,0,0,255]], dtype=np.ubyte)
        cmap = pg.ColorMap(pos, color)
        pg.colormap
        lut = cmap.getLookupTable(0.0, 1.0, 256)

        # set colormap
        self.img.setLookupTable(lut)
        self.img.setLevels([0,100])

        # setup the correct scaling for y-axis
        freq = np.arange((CHUNKSZ/2)+1)/(float(CHUNKSZ)/FS)
        yscale = 1.0/(self.img_array.shape[1]/freq[-1])

        self.img.scale((1./FS)*CHUNKSZ, yscale)

        self.setLabel('left', 'Frequency', units='Hz')

        # prepare window for later use
        self.win = np.hanning(CHUNKSZ)
        #self.show()

    def update(self, chunk):
        # normalized, windowed frequencies in data chunk
        spec = np.fft.rfft(chunk*self.win) / CHUNKSZ
        # get magnitude 
        psd = abs(spec)
        # convert to dB scaleaxis
        psd = 20 * np.log10(psd)

        # roll down one and replace leading edge with new data
        self.img_array = np.roll(self.img_array, -1, 0)
        self.img_array[-1:] = psd

        self.img.setImage(self.img_array, autoLevels=False)

if __name__ == '__main__':
    app = QtGui.QApplication([])


    win = pg.GraphicsWindow(title="Basic plotting examples")
    #win.resize(1000,600)


    w = SpectrogramWidget()
    w.read_collected.connect(w.update)

    spectrum1 = win.addPlot(title="Spectrum 1")#win.addViewBox()

    item = w.getPlotItem()

    spectrum1.addItem(item)


    w2 = SpectrogramWidget2()
    w2.read_collected.connect(w2.update)

    spectrum2 = win.addViewBox()
    spectrum2.addItem(w2.getPlotItem())

    mic = MicrophoneRecorder(w.read_collected)
    mic2 = MicrophoneRecorder(w2.read_collected)

    # time (seconds) between reads
    interval = FS/CHUNKSZ

    t = QtCore.QTimer()
    t.timeout.connect(mic.read)
    t.start((1000/interval) ) #QTimer takes ms

    t2 = QtCore.QTimer()
    t2.timeout.connect(mic2.read)
    t2.start((1000/interval) ) #QTimer takes ms

    app.exec_()
    mic.close()

感谢您的帮助!

最佳答案

我不知道为什么这样做会导致镜像,但问题与使用另一个图中的绘图项有关(我认为这就是您正在做的事情?)

无论如何,PlotWidget不应该这样使用。它们只是普通的 Qt Widget,因此将它们添加到 Qt 布局中,就像使用任何其他 Qt Widget 一样。

if __name__ == '__main__':
    app = QtGui.QApplication([])

    win = QtGui.QMainWindow()
    widget = QtGui.QWidget()
    win.setCentralWidget(widget)
    layout = QtGui.QHBoxLayout(widget)
    win.show()

    w = SpectrogramWidget()
    w.read_collected.connect(w.update)
    layout.addWidget(w)

    w2 = SpectrogramWidget2()
    w2.read_collected.connect(w2.update)
    layout.addWidget(w2)

    # .... etc

附注有两个相同的类但名称不同的原因吗?您可以实例化同一类的多个副本。例如

w = SpectrogramWidget()
w2 = SpectrogramWidget()

关于python - 我的 PyQt 图的 Y 轴是颠倒的(甚至是文本)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40374738/

相关文章:

python - 如何记录 Python 交互式 shell session 中发生的一切?

r - 带有 ggvis : how to plot multiple groups with different shape markers and corresponding fitted regression lines 的 R 中的散点图

java - JAVA 中的实时文本流

Python ping 脚本在第一次尝试时总是失败

Python JSON 到 CSV - 编码错误,UnicodeDecodeError : 'charmap' codec can't decode byte

python - 如何在 Jupyter Notebook 和 Python 中创建交互式绘图

real-time - Apache 弗林克 : Multiple Window Aggregations and Late Data

java - Etherpad 的时间线功能如何工作?

python - 分组并查找属于 n 个唯一最大值的所有值

pandas - 围绕 Seaborn FacetGrid 轴绘制框