使用pyqtgraph进行python实时绘图

fma*_*ngo 3 python plot real-time pyqtgraph

我需要实时绘制来自串行端口的一系列浮点数。这些值由'\ n'字符分隔,因此数据序列如下所示:x1 x2 x3 ...

您将如何绘制数据? 我正在使用Arduino板,数据速率为200个样本/秒,并且我的PC在Windows7 64位上运行。我认为一个不错的选择是使用pyqtgraph库。我开始在pyqtgraph中使用Plotting.py示例(在安装pyqtgraph然后运行之后,可以使用更多示例python3 -m pyqtgraph.examples),但是我不知道如何根据我的需要调整此代码(请参见下文)。提前非常感谢您。

from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg

# Set graphical window, its title and size
win = pg.GraphicsWindow(title="Sample process")
win.resize(1000,600)
win.setWindowTitle('pyqtgraph example')

# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)

# Random data process
p6 = win.addPlot(title="Updating plot")
curve = p6.plot(pen='y')
data = np.random.normal(size=(10,1000)) #  If the Gaussian distribution shape is, (m, n, k), then m * n * k samples are drawn.

# plot counter
ptr = 0 

# Function for updating data display
def update():
    global curve, data, ptr, p6
    curve.setData(data[ptr%10])
    if ptr == 0:
        p6.enableAutoRange('xy', False)  ## stop auto-scaling after the first data set is plotted
    ptr += 1

# Update data display    
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(50)


## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
Run Code Online (Sandbox Code Playgroud)

fma*_*ngo 9

这是正常工作的代码。主要过程包含在update()函数中。它从串行端口读取输入值,更新数组Xm(包含输入值),然后更新其关联的曲线。

张贴此代码是为了简单起见,并且仅适用于低数据速率(少于100个样本/秒)。为了获得更高的数据速率,应在update()函数中进行如下修改。应该从串行端口读取一组值(而不是单个值)。然后,应将此集合附加到数组Xm

希望这个答案对您有用,也非常感谢您的帮助!

# Import libraries
from numpy import *
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import serial

# Create object serial port
portName = "COM12"                      # replace this port name by yours!
baudrate = 9600
ser = serial.Serial(portName,baudrate)

### START QtApp #####
app = QtGui.QApplication([])            # you MUST do this once (initialize things)
####################

win = pg.GraphicsWindow(title="Signal from serial port") # creates a window
p = win.addPlot(title="Realtime plot")  # creates empty space for the plot in the window
curve = p.plot()                        # create an empty "plot" (a curve to plot)

windowWidth = 500                       # width of the window displaying the curve
Xm = linspace(0,0,windowWidth)          # create array that will contain the relevant time series     
ptr = -windowWidth                      # set first x position

# Realtime data plot. Each time this function is called, the data display is updated
def update():
    global curve, ptr, Xm    
    Xm[:-1] = Xm[1:]                      # shift data in the temporal mean 1 sample left
    value = ser.readline()                # read line (single value) from the serial port
    Xm[-1] = float(value)                 # vector containing the instantaneous values      
    ptr += 1                              # update x position for displaying the curve
    curve.setData(Xm)                     # set the curve with this data
    curve.setPos(ptr,0)                   # set x position in the graph to 0
    QtGui.QApplication.processEvents()    # you MUST process the plot now

### MAIN PROGRAM #####    
# this is a brutal infinite loop calling your realtime data plot
while True: update()

### END QtApp ####
pg.QtGui.QApplication.exec_() # you MUST put this at the end
##################
Run Code Online (Sandbox Code Playgroud)

  • 对于那些不想使用 com 端口只是为了尝试示例的人,您可以注释掉 `import serial` 和 `ser = serial.Serial(portName,baudrate)` 行。然后“from random import randrange,uniform”并将“value = ser.readline()”替换为“value=uniform(0, 10)”。不过,很好的例子。 (4认同)