首页 > 解决方案 > 如何在 pyqtgraph 中设置跟踪名称?

问题描述

我正在使用这个类来绘制跟踪,我有 2 行要跟踪,但是我不能显示每行的名称,怎么办?

class Plot2D():
    def __init__(self):
        self.traces = dict()

        #QtGui.QApplication.setGraphicsSystem('raster')
        self.app = QtGui.QApplication([])
        #mw = QtGui.QMainWindow()
        #mw.resize(800,800)

        self.win = pg.GraphicsWindow(title="Detecting cluck")
        self.win.resize(1000,600)
        self.win.setWindowTitle('Detecting')
        # Enable antialiasing for prettier plots
        pg.setConfigOptions(antialias=True)

        self.canvas = self.win.addPlot(title="改装车检测")
        self.canvas.setYRange(0, 1)

    def start(self):
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()

    def trace(self,name,dataset_x,dataset_y,sColor):
        if name in self.traces:
            self.traces[name].setData(dataset_x,dataset_y)
        else:
            self.traces[name] = self.canvas.plot(
                pen=pg.mkPen(sColor, width=3), name="car")

我得到了什么:

我得到了什么

我想要的是:

在此处输入图像描述

标签: pythonpyqtgraph

解决方案


addLegend()除了在图中建立名称之外,您还必须使用:

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

class Plot2D():
    def __init__(self):
        self.traces = dict()

        self.app = QtGui.QApplication([])

        self.win = pg.GraphicsWindow(title="Detecting")
        self.win.resize(1000,600)
        pg.setConfigOptions(antialias=True)

        self.canvas = self.win.addPlot(title="改装车检测")
        self.canvas.addLegend()
        self.canvas.setYRange(0, 1)

    def start(self):
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()

    def trace(self,name,dataset_x,dataset_y,sColor):
        if name in self.traces:
            self.traces[name].setData(dataset_x,dataset_y)
        else:
            self.traces[name] = self.canvas.plot(dataset_x, dataset_y,
                pen=pg.mkPen(sColor, width=3), name=name)

if __name__ == '__main__':
    p = Plot2D()
    p.trace("name1", range(100), 0.5 + np.random.normal(size=100, scale=0.1), 'r')
    p.trace("name2", range(100), 0.5 + np.random.normal(size=100, scale=0.1), 'w')
    p.start()

在此处输入图像描述

更新:

如果要更改字体大小,可以使用 HTML

self.traces[name] = self.canvas.plot(dataset_x, dataset_y,
    pen=pg.mkPen(sColor, width=3), name='''<font size="15">{}</font>'''.format(name))

在此处输入图像描述


推荐阅读