Search code examples
pythonpython-2.7pyqtpyqt4pyqtgraph

How to add custom AxisItem to existing PlotWidget?


I'm trying to add custom AxisItem in pyqtgraph to existing PlotWidget that was generated by Qt Designer. There is related topic here, but there is no exact answer with code example and I cannot comment, so I've created a new topic.

This is my custom AxisItem (based on this code):

import pyqtgraph as pg
import datetime

def int2td(ts):
    return(datetime.timedelta(seconds=float(ts)/1e6))

class TimeAxisItem(pg.AxisItem):
    def __init__(self, *args, **kwargs):
        super(TimeAxisItem, self).__init__(*args, **kwargs)
    def tickStrings(self, values, scale, spacing):
        return [int2dt(value).strftime("%H:%M:%S") for value in values]

This is my main QtPlotter class:

from pyqtgraph.Qt import QtGui
from template_pyqt import Ui_Form # Ui_Form is generated by Qt Designer

class QtPlotter:
    def __init__(self):
        self.app = QtGui.QApplication([])
        self.win = QtGui.QWidget()
        self.ui = Ui_Form()
        self.ui.setupUi(self.win)
        self.win.show()

        self.ui_plot = self.ui.plot 
        self.ui_plot.showGrid(x=True, y=True)

And then I'm trying to add my custom AxisItem:

self.ui_plot.getPlotItem().axes['bottom']['item'] = TimeAxisItem(orientation='bottom')

I have no errors, but this does not give any effect.


Solution

  • It was so easy. The PlotItem class does not have a setAxis method. Instead of that there is a method named setAxisItems. this code worked for me.

    date_axis = pg.graphicsItems.DateAxisItem.DateAxisItem(orientation = 'bottom')
    self.mainSoundPlot.setAxisItems(axisItems = {'bottom': date_axis})