admin管理员组

文章数量:1293520

I am trying to use pyqtgraphs DateAxisItem for relative times on the x axis, i.e., durations (which can be between a few hours and several days). I know I could simply use an ordinary AxisItem and show the durations of the type datetime.timedelta in seconds (see the MWE below). However, I want the x axis labels to have a more conventient (adaptable) format "DD HH:MM:SS" (e.g. "00 23:31:29") instead of large floats (e.g. 6132689.0). How could I achieve that? Or is AxisItem more suitable for this? If so, how can I adapt the x labels to this format?

from datetime import datetime
import pyqtgraph as pg

app = pg.mkQApp("DateAxisItem Example")

# Create a plot with a date-time axis
w = pg.PlotWidget(axisItems = {'bottom': pg.DateAxisItem()})
w.showGrid(x=True, y=True)

x_ref = datetime(2024, 1, 1, 12, 10, 22)

x_absolute = [datetime(2024, 2, 11, 9, 36, 50), 
            datetime(2024, 3, 12, 11, 41, 51),
            datetime(2024, 4, 13, 16, 51, 51),
            datetime(2024, 5, 14, 18, 58, 52)]

x_relative = [(value - x_ref).total_seconds() for value in x_absolute]

ydata = [10, 9, 12, 11]

# the x axis shows absolute time values instead of relative
w.plot(x_relative, ydata)

w.setWindowTitle('pyqtgraph example: DateAxisItem')
w.show()

if __name__ == '__main__':
    pg.exec()

EDIT: If I use AxisItem, I would need to fix overlapping labels and the ticks in between are missing which I am not sure is a good path:

from datetime import datetime, timedelta
import pyqtgraph as pg

app = pg.mkQApp("DateAxisItem Example")

ax = pg.AxisItem(orientation="bottom")
w = pg.PlotWidget(axisItems = {'bottom': ax})
w.showGrid(x=True, y=True)

x_ref = datetime(2024, 1, 1, 12, 10, 22)

x_absolute = [datetime(2024, 2, 11, 9, 36, 50), 
            datetime(2024, 3, 12, 11, 41, 51),
            datetime(2024, 4, 13, 16, 51, 51),
            datetime(2024, 5, 14, 18, 58, 52)]

x_relative = [(value - x_ref).total_seconds() for value in x_absolute]


dx = [(D, str(timedelta(seconds=D)).replace(" days,", "d")) for D in x_relative]
ax.setTicks([dx, []])

ydata = [10, 9, 12, 11]

w.plot(x_relative, ydata)

w.setWindowTitle('pyqtgraph example: DateAxisItem')
w.show()

if __name__ == '__main__':
    pg.exec()

本文标签: