Search code examples
python-3.xpyqt5pyqtgraph

PyQt5 gui with PyQtGraph plot: Display y axis on the right


I am creating a PyQt5 Gui and I am using PyQtGraph to plot some data. Here is a minimal, complete, verifiable example script that closely resembles the structure that I have.

import sys
from PyQt5.QtWidgets import (QWidget, QGridLayout, QApplication)
import pyqtgraph as pg
from pyqtgraph import QtCore, QtGui

class CustomPlot(pg.GraphicsObject):
    def __init__(self, data):
        pg.GraphicsObject.__init__(self)
        self.data = data
        print(self.data)
        self.generatePicture()

    def generatePicture(self):
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen('w', width=1/2.))
        for (t, v) in self.data:
            p.drawLine(QtCore.QPointF(t, v-2), QtCore.QPointF(t, v+2))
        p.end()

    def paint(self, p, *args):
        p.drawPicture(0, 0, self.picture)

    def boundingRect(self):
        return QtCore.QRectF(self.picture.boundingRect())


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.simpleplot()

    def initUI(self):
        self.guiplot = pg.PlotWidget()
        layout = QGridLayout(self)
        layout.addWidget(self.guiplot, 0,0)

    def simpleplot(self):
        data = [
            (1., 10),
            (2., 13),
            (3., 17),
            (4., 14),
            (5., 13),
            (6., 15),
            (7., 11),
            (8., 16)
        ]
        pgcustom = CustomPlot(data)
        self.guiplot.addItem(pgcustom)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

This generates a graph that looks like enter image description here

The y-axis is on the left of the plot but I would like to move it to the right. I have tried a number of things but I cannot find the object (QtGui.QPainter, GraphicObject, etc.) that has the option or method to achieve this.


Solution

  • It can be set by methods of the PlotItem class.

    def initUI(self):
        self.guiplot = pg.PlotWidget()
        plotItem = self.guiplot.getPlotItem()
        plotItem.showAxis('right')
        plotItem.hideAxis('left')
    

    If you haven't read the section on Organization of Plotting Classes, take look at it. In particular at the relation between the PlotWidet and PlotItem classes.