Dear all,
Please find below few lines of code showing the workaround I use to have the legend of all the curves from a multiple axes plot.
I would like to merge all legends in one frame only. This can be done using
legend.addItem() also for the curve created via PlotItem (the 1st one), however, the following error is raised:
opts = self.item.opts
AttributeError: 'PlotItem' object has no attribute 'opts'
This issue was reported here,
https://groups.google.com/forum/#!topic/pyqtgraph/1PrA5VS4sy8 with Luke mentioning: ...legend.addItem() requires a PlotCurveItem or PlotDataItem...
which is not the case for the 1st curve.
Please let me know if there a way to combine all legends together.
Regards,
Joao Saraiva
# -*- coding: utf-8 -*-
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
app = QtGui.QApplication([])
pw = pg.GraphicsView()
l = pg.GraphicsLayout()
pw.setCentralItem(l)
pw.show()
plt1 = pg.PlotItem(title="MultipleAxePlotWithLegend")
l.addItem(plt1)
plt1.addLegend()
plt1.plot([1,2,4,8,16,32], pen='g', name='legend from PlotItem')
plt1.setLabels(left='axis 1', bottom='time')
legend = pg.LegendItem(offset=(-30,30))
plt2 = pg.ViewBox()
legend.setParentItem(plt2)
plt1.showAxis('right')
plt1.scene().addItem(plt2)
plt1.getAxis('right').linkToView(plt2)
plt2.setXLink(plt1)
a=pg.PlotDataItem([1,5,11,15], symbol='t')
plt2.addItem(a)
legend.addItem(a,"legend from viewBox2")
plt3 = pg.ViewBox()
legend.setParentItem(plt3)
ax3 = pg.AxisItem('right')
plt1.layout.addItem(ax3, 2, 3)
plt1.scene().addItem(plt3)
ax3.linkToView(plt3)
plt3.setXLink(plt1)
b=pg.PlotCurveItem([11,25,26], pen='r')
plt3.addItem(b)
legend.addItem(b,"legend from viewBox3")
def updateViews():
global plt1, plt2, plt3
plt2.setGeometry(plt1.vb.sceneBoundingRect())
plt2.linkedViewChanged(plt1.vb, plt2.XAxis)
plt3.setGeometry(plt1.vb.sceneBoundingRect())
plt3.linkedViewChanged(plt1.vb, plt3.XAxis)
updateViews()
plt1.vb.sigResized.connect(updateViews)
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()