Adding a Legent to ViewBox for the GraphicsView

24 views
Skip to first unread message

Syed Fahad Iqbal

unread,
Nov 8, 2020, 3:11:19 AM11/8/20
to pyqtgraph
Hello,
How can I add a legend for the plot using ViewBox. I'm having a multiple plots and I would like to have a single legend item for both the curves togather
Following is the Code:

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

pg.mkQApp()
pw = pg.GraphicsView()
pw.setWindowTitle('pyqtgraph example: multiple y-axis')


# Axis
a2 = pg.AxisItem("left")

# ViewBoxes
v2 = pg.ViewBox()

# main view
pw.show()

# layout
l = pg.GraphicsLayout()
pw.setCentralWidget(l)

# add axis to layout
## watch the col parameter here for the position
l.addItem(a2, rowspan=1, colspan=1)

# plotitem and viewbox
## at least one plotitem is used whioch holds its own viewbox and left axis
pI = pg.PlotItem()
v1 = pI.vb # reference to viewbox of the plotitem
l.addItem(pI, rowspan=1, colspan=1) # add plotitem to layout


# add viewboxes to layout
l.scene().addItem(v2)

# link axis with viewboxes
a2.linkToView(v2)


# axes labels
pI.getAxis("left").setLabel('axis 1 in ViewBox of PlotItem', color='#FFFFFF')
a2.setLabel('axis 2 in Viewbox 2', color='#2E2EFE')

# slot: update view when resized
def updateViews():
v2.setGeometry(v1.sceneBoundingRect())

# data
x1 = [1,2,3,4,5,6]
x2 = [1,2,3,4,5,6,7,8,9,10,12,14,16,18]

y1 = [0,4,6,8,10,4]
y2 = [0,5,7,9,11,3,5,6,0,8,9,4,6,8]



# plot
v1.addItem(pg.PlotCurveItem(x1, y1, pen='#FFFFFF'))
v2.addItem(pg.PlotCurveItem(x2, y2, pen='#2E2EFE'))


# updates when resized
v1.sigResized.connect(updateViews)

# autorange once to fit views at start
v2.enableAutoRange(axis= pg.ViewBox.XYAxes, enable=True)

updateViews()

if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()


Reply all
Reply to author
Forward
0 new messages