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_()
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})
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
PS: It would be really nice to see the PR, mentioned by Luke, to be finally merged.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With