Changing ticks in pyqtgraph objects to strings

Heads up! You've already completed this tutorial.

tidyhooker9418 | 2021-01-08 20:27:47 UTC | #1

https://www.pythonguis.com/tutorials/plotting-pyqtgraph/

Is there a way to change the tics in a line graph to dates or names of months?


martin | 2021-01-14 14:08:56 UTC | #2

Hey, here you go.

python
from PyQt5 import QtWidgets
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg
import sys  # We need sys so that we can pass argv to QApplication
import os
import datetime

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)

        months = [1,2,3,4,5,6,7,8,9,10]
        temperature = [30,32,34,32,33,31,29,32,35,45]

        self.graphWidget.setBackground('w')

        pen = pg.mkPen(color=(255, 0, 0))

        month_labels = [
            # Generate a list of tuples (x_value, x_label)
            (m, datetime.date(2020, m, 1).strftime('%B'))
            for m in months
        ]
        self.graphWidget.plot(months, temperature, pen=pen, labels=month_labels)

        ax=self.graphWidget.getAxis('bottom')
        # Pass the list in, *in* a list.
        ax.setTicks([month_labels])


def main():
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

The trick is the labels need to be a list of 2-tuples containing the tick value (x value) and the label for that tick. In the example above we're using month numbers 1-10 for the x-axis, so the month labels becomes [(1, "January"), (2, "February"), (3, "March") ... etc]

To set the labels you need to get the axis object, and then use .setTicks() ...since this can be used to set ticks for both axes, you need to pass it in in a list i.e. [month_labels] where month_labels is our list of tick labels.

Create GUI Applications with Python & Qt5 by Martin Fitzpatrick — (PyQt5 Edition) The hands-on guide to making apps with Python — Over 15,000 copies sold!

More info Get the book

The result is ...

month_ticks|618x500

The complete guide to packaging Python GUI applications with PyInstaller.
[[ discount.discount_pc ]]% OFF for the next [[ discount.duration ]] [[discount.description ]] with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses with code [[ discount.coupon_code ]]

Hope that helps?


Create GUI Applications with Python & Qt6 by Martin Fitzpatrick — (PyQt6 Edition) The hands-on guide to making apps with Python — Over 15,000 copies sold!

More info Get the book

Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak
Martin Fitzpatrick

Changing ticks in pyqtgraph objects to strings was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt. Martin founded PythonGUIs to provide easy to follow GUI programming tutorials to the Python community. He has written a number of popular Python books on the subject.