set dynamic ticks on QtCharts.QDateTimeAxis

587 Views Asked by At

I'm using Qt5 (via pyside2) to draw a "money/time" chart application.

I can draw the data and now I'm trying to set the axis. I have set the y axis with a QValueAxis that support dynamic ticks, so I can say "draw a tick every 10000 €"

axis_y = QtCharts.QValueAxis()
axis_y.setTickType(QtCharts.QValueAxis.TicksDynamic)
axis_y.setTickAnchor(0.)
axis_y.setTickInterval(10000.)
axis_y.setMinorTickCount(9)
self.addAxis(axis_y, Qt.AlignLeft)

I cannot achieve the same results with the x axis. I'm using QDateTimeAxis but it seems to me it lacks any way to set the ticks dynamically.

what I want to achieve is: "draw a major tick at the january, 1 of each year, and a minor tick at the start of each month".

1

There are 1 best solutions below

0
On BEST ANSWER

This is really not the right approach[0], but as a fast and "achievable" work around, you can replace the QDateTimeAxis with a QCategoryAxis and populate the various "categories" as (for example) the years where the data is available (+- some year before and after).

axis_x = QtCharts.QCategoryAxis()
axis_x.setLabelsPosition(QtCharts.QCategoryAxis.AxisLabelsPositionOnValue)
for dt in years(data):
    axis_x.append(f'{dt}', ts(dt))
self.addAxis(axis_x, Qt.AlignBottom)
series.attachAxis(axis_x)

where years yield the years of the data (as date objects) and ts extract the EPOCH timestamp

[0] From what I understand the only "real" solution is to ditch QtCharts and rely on Qwt to draw the chart