pyqt5开发(3)PyQtGraph 绘图

PyQtGraph 绘图

 http://www.python3.vip/tut/py/gui/pyqtgraph-1/
 

Python语言 的数据可视化(绘图) 方法,常见的有 Matplotlib 和 PyQtGraph

  • Matplotlib

说到 Python语言 的数据作图, Matplotlib 当然是最有名的。

优点: 功能完备、成熟稳定、社区生态圈庞大。

缺点: 某些作图场景性能不高,和Qt图形界面框架 融合的不太好。

  • PyQtGraph

PyQtGraph 是基于Qt 的纯Python 库。

优点: 大数据量的作图性能远高于 Matplotlib, 动态更新图的性能也比Matplotlib高。

并且和Qt图形界面框架完美融合,因为它就是基于Qt开发的。

缺点: 作图功能没有Matplotlib多,开发社区没有Matplotlib大。


那么,我们应该使用哪种方案呢?我的建议是:

如果你已经使用Qt开发图形界面程序了,并且作图功能是PyQtGraph支持的, 建议使用 PyQtGraph,因为它和Qt界面无缝结合。

否则 使用 Matplotlib。


本文先介绍 PyQtGraph 的使用示例。

PyQtGraph 安装

pip install pyqtgraph

 

官方案例

PyQtGraph 官方文档包含了很多示例代码,我们只需运行如下代码,即可查看这些demo和对应的代码

import pyqtgraph.examples
pyqtgraph.examples.run()

  

 

XY 轴曲线图 demo

嵌入到Qt程序界面中

from PySide2 import QtWidgets
import pyqtgraph as pg

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super().__init__()

        self.setWindowTitle('pyqtgraph作图示例')

        # 创建 PlotWidget 对象
        self.pw = pg.PlotWidget()

        # 设置图表标题
        self.pw.setTitle("气温趋势",
                         color='008080',
                         size='12pt')

        # 设置上下左右的label
        self.pw.setLabel("left","气温(摄氏度)")
        self.pw.setLabel("bottom","时间")

        # 设置Y轴 刻度 范围
        self.pw.setYRange(min=-10, # 最小值
                          max=50)  # 最大值


        # 显示表格线
        self.pw.showGrid(x=True, y=True)

        # 背景色改为白色
        self.pw.setBackground('w')

        # 居中显示 PlotWidget
        self.setCentralWidget(self.pw)

        hour = [1,2,3,4,5,6,7,8,9,10]
        temperature = [30,32,34,32,33,31,29,32,35,45]

        # hour 和 temperature 分别是 : x, y 轴上的值
        self.pw.plot(hour, 
                     temperature,
                     pen=pg.mkPen('b') # 线条颜色
                    )

if __name__ == '__main__':
    app = QtWidgets.QApplication()
    main = MainWindow()
    main.show()
    app.exec_()

  

实时更新图

要画动态的实时更新图,只需要在把变更的内容重新plot即可。

示例代码如下

from PySide2 import QtWidgets
from pyqtgraph.Qt import  QtCore
import pyqtgraph as pg
import sys
from random import randint

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super().__init__()

        self.setWindowTitle('pyqtgraph作图')

        # 创建 PlotWidget 对象
        self.pw = pg.PlotWidget()

        # 设置图表标题
        self.pw.setTitle("气温趋势",
                         color='008080',
                         size='12pt')

        # 设置上下左右的label
        self.pw.setLabel("left","气温(摄氏度)")
        self.pw.setLabel("bottom","时间")

        # 设置Y轴 刻度 范围
        self.pw.setYRange(min=-10, # 最小值
                          max=50)  # 最大值

        # 显示表格线
        self.pw.showGrid(x=True, y=True)

        # 背景色改为白色
        self.pw.setBackground('w')

        # 设置Y轴 刻度 范围
        self.pw.setYRange(min=-10, # 最小值
                          max=50)  # 最大值

        # 居中显示 PlotWidget
        self.setCentralWidget(self.pw)

        # 实时显示应该获取 plotItem, 调用setData,
        # 这样只重新plot该曲线,性能更高
        self.curve = self.pw.getPlotItem().plot(
            pen=pg.mkPen('r', width=1)
        )

        self.i = 0
        self.x = [] # x轴的值
        self.y = [] # y轴的值

        # 启动定时器,每隔1秒通知刷新一次数据
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateData)
        self.timer.start(1000)

    def updateData(self):
        self.i += 1
        self.x.append(self.i)
        # 创建随机温度值
        self.y.append(randint(10,30))

        # plot data: x, y values
        self.curve.setData(self.x,self.y)

if __name__ == '__main__':
    app = QtWidgets.QApplication()
    main = MainWindow()
    main.show()
    app.exec_()

  

轴刻度为字符串

上面的程序运行起来, X轴的刻度是 数字, 如果我们希望轴刻度是文字怎么做呢?

我们参考了这个网址的介绍: https://stackoverflow.com/questions/31775468/show-string-values-on-x-axis-in-pyqtgraph?lq=1

需要定义从数字到字符串的映射列表,参考如下代码

import pyqtgraph as pg

# 刻度表,注意是双层列表
xTick = [[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')]]
x = [0,1,2,3,4,5]
y = [1, 2, 3, 4, 5, 6]

win = pg.GraphicsWindow()
stringaxis = pg.AxisItem(orientation='bottom')
stringaxis.setTicks(xTick)
plot = win.addPlot(axisItems={'bottom': stringaxis})
curve = plot.plot(x,y)

pg.QtGui.QApplication.exec_()

  

获取鼠标所在处刻度值

有时候,我们的程序需要获取 鼠标在 pyqtgraph 图形上移动时,鼠标所在对应的数据是什么。

可以参考下面代码的作法

import pyqtgraph as pg
import PySide2

x = [1,2,3,4,5]
y = [1,2,3,4,5]

win = pg.GraphicsWindow()
plot = win.addPlot()
curve = plot.plot(x,y)

def mouseover(pos):
    act_pos = curve.mapFromScene(pos)
    if type(act_pos) != PySide2.QtCore.QPointF:
        return
    print(act_pos.x(),act_pos.y())
    # 有了 act_pos的坐标值,就可以根据该值处理一些信息
    # 比如状态栏展示 该处的 日期等

curve.scene().sigMouseMoved.connect(mouseover)

pg.QtGui.QApplication.exec_()

  

原文地址:https://www.cnblogs.com/kekeoutlook/p/14002151.html