pyqtgraph中PlotWidget绘图的图例标签无法正常显示问题求助
pyqtgraph PlotWidget绘图图例不显示问题及解决
问题描述
我在开发基于pyqtgraph的UI应用时,绘图的曲线标签无法正常显示,尝试多种方法都没解决,推测是PlotWidget和pyqtgraph组合使用的方法有误,特此咨询问题根源。
下面是可复现问题的示例代码,功能是绘制两条分别带叉形、圆点标记的曲线,但代码里设置的result number 1和result number 2标签始终不显示:
import numpy as np from pyqtgraph.Qt import QtGui, uic uifilename = 'testUI211014.ui' form_class = uic.loadUiType(uifilename)[0] class MyWindowClass(QtGui.QMainWindow, form_class): def __init__(self): QtGui.QMainWindow.__init__(self) self.setupUi(self) if __name__ == '__main__': app = QtGui.QApplication([]) win = MyWindowClass() x = np.arange(10) y1 = x**1.5 y2 = x**2 win.graphicsView.plot(x,y1, label='result number 1',symbol='x') win.graphicsView.plot(x,y2, label='result number 2',symbol='o') win.graphicsView.setLabel('bottom', text='x') win.graphicsView.setLabel('left', text='y') win.show() app.exec_()
运行后无标签显示,我期望得到类似matplotlib的常规图例:带边框、字号合适、清晰标注各曲线含义。
我曾尝试在win.show()前插入如下代码使用LabelItem:
import pyqtgraph as pg labelValue = pg.LabelItem('result number 1') win.graphicsView.addItem(labelValue)
但显示的result number 1字号过大、倒置、无边框,不符合使用需求。
所用UI文件内容
所用的testUI211014.ui文件仅在主窗口中嵌入了一个PlotWidget,内容如下:
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>MainWindow</class> <widget class="QMainWindow" name="MainWindow"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>800</width> <height>600</height> </rect> </property> <property name="windowTitle"> <string>MainWindow</string> </property> <widget class="QWidget" name="centralwidget"> <widget class="PlotWidget" name="graphicsView"> <property name="geometry"> <rect> <x>30</x> <y>20</y> <width>671</width> <height>471</height> </rect> </property> </widget> </widget> <widget class="QMenuBar" name="menubar"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>800</width> <height>42</height> </rect> </property> </widget> <widget class="QStatusBar" name="statusbar"/> </widget> <customwidgets> <customwidget> <class>PlotWidget</class> <extends>QGraphicsView</extends> <header>pyqtgraph</header> </customwidget> </customwidgets> <resources/> <connections/> </ui>
版本兼容问题说明
2021年10月18日更新:
上述测试在Python 3.5环境下运行,切换到Python 3.9环境运行同一段代码时,甚至连曲线都不显示,疑似存在版本兼容问题。
问题排查及解决方案
2021年11月2日更新:
- 之前遗漏说明:和matplotlib用法一致的常规
addLegend()指令无效,运行后无图例显示也无报错信息。 - 已找到可行解决方案:删除原有的带label参数的plot调用,替换为如下代码,放在
show()之前即可正常显示图例:
c1 = win.graphicsView.plot(x,y1,symbol='x') c2 = win.graphicsView.plot(x,y2,symbol='o') import pyqtgraph as pg legend = pg.LegendItem((80, 60), offset=(70, 20)) legend.setParentItem(win.graphicsView.graphicsItem()) legend.addItem(c1, 'result number 1') legend.addItem(c2, 'result number 2')
目前标签显示问题已解决,但暂不清楚addLegend()失效的原因。
内容的提问来源于stack exchange,提问作者Stéphane
相关产品推荐
相关产品推荐

