Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting Datetime objects with PyQtGraph

I am new to PyQtGraph and need help plotting datetime objects on the x-axis which can easily be done with matplotlib. Any help would be appreciated.

As a simple version of what Id like to do see below where I want to plot the datetime objects displayed as the ticks on the x-axis.

The code throws an error as this cannot be done.

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import datetime

datetimes = ['2014-10-01 00:00:00', '2014-10-02 00:00:00', '2014-10-03 00:00:00']
x = [datetime.datetime.strptime(i, '%Y-%m-%d %H:%M:%S') for i in datetimes]
y = [1,2,3]


win = pg.GraphicsWindow(title = 'plotting')
p1 = win.addPlot(row=1, col=0, title = 'test')
p1.plot(x,y)

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
like image 833
RicDavimes Avatar asked Apr 01 '15 08:04

RicDavimes


2 Answers

pyqtgraph now natively supports DateTime format: https://pyqtgraph.readthedocs.io/en/latest/graphicsItems/dateaxisitem.html?highlight=DateAxisItem

It is quite straightforward, if you have timestamps on the x-axis, just do:

axis = DateAxisItem()
plot.setAxisItems({'bottom':axis})
like image 136
dumkar Avatar answered Oct 11 '22 01:10

dumkar


A working example with custom AxisItem on git: pg_time_axis.py.

If using PyQt5, change the import in the __main__ function to from PyQt5 import QtGui

datetime axis zoom 1 datetime axis zoom 2

PS: It would be really nice to see the PR, mentioned by Luke, to be finally merged.

like image 35
queezz Avatar answered Oct 11 '22 02:10

queezz