1

I'm working with QTCustomPlot library on Qt and I have to show all x axis values in my plot.

These are the properties of the axis:

    ui->dateTimePlot->addGraph();
    ui->dateTimePlot->graph()->data()->set(timeData);

    // configure bottom axis to show date instead of number:
    QSharedPointer<QCPAxisTickerDateTime> dateTicker(new QCPAxisTickerDateTime);
    dateTicker->setDateTimeFormat("d/M/yyyy h:m:s");
    dateTicker->setTickStepStrategy(QCPAxisTicker::TickStepStrategy::tssMeetTickCount);

    // x axis
    ui->dateTimePlot->xAxis->setTicker(dateTicker);
    ui->dateTimePlot->xAxis->setTickLabelRotation(60);
    ui->dateTimePlot->xAxis->setTickLabels(true);
    QDateTime from = QDateTime::fromString(listCounters.first()->getDate() + " " + listCounters.first()->getTime(), "d/M/yyyy h:m:s");
    QDateTime to = QDateTime::fromString(listCounters.last()->getDate() + " " + listCounters.last()->getTime(), "d/M/yyyy h:m:s");
    ui->dateTimePlot->xAxis->setRange(from.toSecsSinceEpoch(), to.toSecsSinceEpoch());

    // y axis
    ui->dateTimePlot->yAxis->setRange(0, 300);

and this is the plot: My plot image

the problem is that my plot doesn't show the dates of every point on x axis.

How can I fix it?

underscore_d
  • 6,309
  • 3
  • 38
  • 64

1 Answers1

1

Create custom ticker and set datetime values as tickvector.

class Ticker : public QCPAxisTickerDateTime {
public:
    void setTickVector(QVector<double>& ticks);
protected:
    QVector<double> createTickVector(double tickStep, const QCPRange &range);
    int getSubTickCount(double tickStep);
    QVector<double> mTicks;
};

void Ticker::setTickVector(QVector<double> &ticks) {
    mTicks = ticks;
}

QVector<double> Ticker::createTickVector(double, const QCPRange&)
{
    return mTicks;
}

int Ticker::getSubTickCount(double)
{
    return 0;
}

void MainWindow::setupPlot() {

    QVector<double> xs;
    QVector<double> ys;
    QDateTime from = QDateTime(QDate(2021,5,8),QTime(0,0,0));
    QDateTime to = QDateTime(QDate(2021,5,10),QTime(0,0,0));
    qint64 from_ = from.toSecsSinceEpoch();
    qint64 to_ = to.toSecsSinceEpoch();
    qint64 range = to_ - from_;
    int n = 30;
    auto* g = QRandomGenerator::global();
    for(int i=0;i<n;i++) {
        xs.append((double) range * i / n + from_);
        ys.append(g->bounded(200.0) + 50.0);
    }

    ui->dateTimePlot->addGraph();
    ui->dateTimePlot->graph()->setData(xs, ys);
    QSharedPointer<Ticker> dateTicker(new Ticker());
    dateTicker->setTickVector(xs);
    dateTicker->setDateTimeFormat("d/M/yyyy h:m:s");

    // x axis
    ui->dateTimePlot->xAxis->setTicker(dateTicker);
    ui->dateTimePlot->xAxis->setTickLabelRotation(60);
    ui->dateTimePlot->xAxis->setTickLabels(true);
    ui->dateTimePlot->xAxis->setRange(from.toSecsSinceEpoch(), to.toSecsSinceEpoch());

    // y axis
    ui->dateTimePlot->yAxis->setRange(0, 300);
}
mugiseyebrows
  • 4,138
  • 1
  • 14
  • 15