Changing ticks in pyqtgraph objects to strings

Heads up! You've already completed this tutorial.

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

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.

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()

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


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

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

        # Pass the list in, *in* a list.

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

if __name__ == '__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 ...


Hope that helps?

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 ]]
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.