import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
# A custom ItemSample to draw in legend
from pyqtgraph.graphicsItems.LegendItem import ItemSample
from pyqtgraph.graphicsItems.ScatterPlotItem import drawSymbol
class MyItemSample(ItemSample):
def __init__(self, item):
super().__init__(item)
def paint(self, p, *args):
opts = self.item.opts
if opts.get('fillLevel',None) is not None and opts.get('fillBrush',None) is not None:
p.setBrush(pg.mkBrush(opts['fillBrush']))
p.setPen(pg.mkPen(None))
p.drawPolygon(QtGui.QPolygonF([QtCore.QPointF(2,10), QtCore.QPointF(18,10), QtCore.QPointF(18,18), QtCore.QPointF(2,18)]))
if not isinstance(self.item, pg.ScatterPlotItem):
p.setPen(pg.mkPen(opts['pen']))
p.drawLine(2, 10, 18, 10)
symbol = opts.get('symbol', None)
if symbol is not None:
if isinstance(self.item, pg.PlotDataItem):
opts = self.item.scatter.opts
pen = pg.mkPen(opts['pen'])
brush = pg.mkBrush(opts['brush'])
size = opts['size']
p.translate(10,10)
path = drawSymbol(p, symbol, size, pen, brush)
plt = pg.plot()
plt.setWindowTitle('pyqtgraph example: Legend')
#legend = plt.addLegend() # Don't use this, instead create and populate legend manually
l = pg.LegendItem((100,60), offset=(70,30)) # args are (size, offset)
l.setParentItem(plt.graphicsItem()) # Note we do NOT call plt.addItem in this case
# Crude patch of the legend paint() method
import types
def paint(self, p, *args):
p.fillRect(self.boundingRect(), pg.mkBrush(192,0,0,50))
l.paint = types.MethodType(paint, l)
# Fix the spacing between legend symbol and text.
# This is probably needs to be added to the __init__() of LegendItem...
l.layout.setHorizontalSpacing(20)
c1 = plt.plot([1,3,2,4], pen='r', symbol='o', symbolPen='r', symbolBrush=0.5, name='red plot')
c2 = plt.plot([2,1,4,3], pen='g', fillLevel=0, fillBrush=(255,255,255,30), name='green plot')
l.addItem(MyItemSample(c1), "my red plot")
l.addItem(MyItemSample(c2), "my green plot")
## 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_()