9

I'm using pyqtgraph and I'd like to add an item in the legend for InfiniteLines.

I've adapted the example code to demonstrate:

# -*- coding: utf-8 -*-
"""
Demonstrates basic use of LegendItem

"""
import initExample ## Add path to library (just for examples; you do not need this)

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

plt = pg.plot()
plt.setWindowTitle('pyqtgraph example: Legend')
plt.addLegend()

c1 = plt.plot([1,3,2,4], pen='r', name='red plot')
c2 = plt.plot([2,1,4,3], pen='g', fillLevel=0, fillBrush=(255,255,255,30), name='green plot')
c3 = plt.addLine(y=4, pen='y')
# TODO: add legend item indicating "maximum value"

## 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_()

What I get as a result is: plot image

How do I add an appropriate legend item?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
MikeyB
  • 3,288
  • 1
  • 27
  • 38

3 Answers3

16

pyqtgraph automatically adds an item to the legend if it is created with the "name" parameter. The only adjustment needed in the above code would be as follows:

c3 = plt.plot (y=4, pen='y', name="maximum value")

as soon as you provide pyqtgraph with a name for the curve it will create the according legend item by itself. It is important though to call plt.addLegend() BEFORE you create the curves.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Tulkas Astaldo
  • 178
  • 1
  • 6
8

For this example, you can create an empty PlotDataItem with the correct color and add it to the legend like this:

style = pg.PlotDataItem(pen='y')
plt.plotItem.legend.addItem(l, "maximum value")
Luke
  • 11,374
  • 2
  • 48
  • 61
0

I don't find the accepted answer satisfactory

Maybe it used to work in 2015, but with my version (pyqtgraph==0.13.3) :

c3 = plt.plot(y=4, pen='y', name="maximum value")

Throw a TypeError and

c3 = plt.addLine(y=4, pen="y", name="maximum value")

doesn't add anything to the legend.

My solution :

  1. You can use label argument. Put some text close to the line, so it's not in the legend box but can be useful.
c3 = plt.addLine(y=4, pen="y", label="maximum value")
  1. You add the legend entry manually, but addLine generate an InfiniteLine which is not compliant. You can however monkey patch it with relatively little effort :
import pyqtgraph as pg

plt = pg.plot()
plt.setWindowTitle("pyqtgraph example: Legend")
legend = plt.addLegend()

c1 = plt.plot([1, 3, 2, 4], pen="r", name="red plot")
c2 = plt.plot(
    [2, 1, 4, 3], pen="g", fillLevel=0, fillBrush=(255, 255, 255, 30), name="green plot"
)
c3 = plt.addLine(y=4, pen="y", name="maximum value")
# legend.addItem expect fist argument to have opts dict
c3.opts = {"pen": "y"}
legend.addItem(c3, "test")

pg.exec()