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(MainWindow, self).__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.

The result is ...

month_ticks|618x500

Hope that helps?


1:1 Coaching & Tutoring for your Python GUIs project
Martin Fitzpatrick Python GUIs Coaching & Training
60 mins ($195) More info

1:1 Python GUIs Coaching & Training

Comprehensive code reviewBugfixes & improvements • Maintainability advice and architecture improvements • Design and usability assessment • Suggestions and tips to expand your knowledgePackaging and distribution help for Windows, Mac & Linux • Find out more.

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

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.