使用qcustomplot
创建绘图后,我如何根据现有X值检索Y值,然后在这些位置绘制点?
我的尝试如下:
创建情节:
此函数创建绘图,在x轴上添加一些数据(日期),在y轴上添加一些值:
void Qt_PlotTest::createPlot(){
QCustomPlot* customPlot = ui.widget;
customPlot->setLocale(QLocale(QLocale::English, QLocale::UnitedKingdom));
//Set some data:
double now = QDateTime::currentDateTime().toTime_t();
QVector<double> yData, xData;
for (int i = 0; i < 100; i++){
xData.push_back(now + i*24.0 * 3600.0);
yData.push_back(pow(double(i), 2) + 550.0*sin(double(i)/4.0));
}
// create graph and assign data to it:
customPlot->addGraph();
customPlot->graph(0)->setData(xData, yData);
//Fix axes:
//Set date axis:
QSharedPointer<QCPAxisTickerDateTime> dateTicker(new QCPAxisTickerDateTime);
dateTicker->setDateTimeFormat("d. MMMM\nyyyy");
customPlot->xAxis->setTicker(dateTicker);
customPlot->xAxis->setLabel("Time");
customPlot->yAxis->setLabel("Value");
customPlot->rescaleAxes();
customPlot->replot();
//Set interations:
customPlot->setInteraction(QCP::iRangeDrag, true);
customPlot->setInteraction(QCP::iRangeZoom, true);
}
结果是:
设置散点图
此函数应根据x值在正确的x / y位置绘制几个散点。 (我需要从现有的图中读取相应的Y值。)
void Qt_PlotTest::setScatterPoints(){
QCustomPlot* customPlot = ui.widget;
//The locations where scatter points should be plotted:
QDate qd1(2018, 03, 26), qd2(2018, 03, 30), qd3(2018, 05, 11), qd4(2018, 06, 15);
QVector<double> dates = { (double)QDateTime(qd1).toTime_t(), (double)QDateTime(qd2).toTime_t(), (double)QDateTime(qd3).toTime_t(), (double)QDateTime(qd4).toTime_t() };
//Use tracer to find data at these dates:
QVector<double> values;
QCPItemTracer *tracer = new QCPItemTracer(customPlot);
tracer->setGraph(customPlot->graph(0));
tracer->setInterpolating(true);
for (int i = 0; i < 4; i++){
tracer->setGraphKey(dates[i]);
values.push_back(tracer->position->coords().y());
}
//Plot points at these locations:
QCPGraph* dwPoints = new QCPGraph(customPlot->xAxis, customPlot->yAxis);
dwPoints->setAdaptiveSampling(false);
dwPoints->setLineStyle(QCPGraph::lsNone);
dwPoints->setScatterStyle(QCPScatterStyle::ssCircle);
dwPoints->setPen(QPen(QBrush(Qt::red), 2));
dwPoints->addData(dates, values);
customPlot->replot();
}
显然QCPItemTracer
没有找到正确的Y值。 (我还有一些我不想要的额外轴。)
我想用QCPItemTracer
来实现我想要的东西吗?我还看到了一些使用QCPDataMap
基于X值查找Y值的示例。但据我所知,QCPDataMap
已不在qcustomplot
。
答案 0 :(得分:1)
我解决了自己的问题:
我不得不调用tracer->updatePosition()
来实际获取放置示踪剂的坐标系中的坐标。
我不想要的轴实际上是最终示踪剂位置处示踪剂的可视化。我只需要致电tracer->setVisibile(false)
来隐藏它。
所以在void Qt_PlotTest::setScatterPoints
我有这个:
QCPItemTracer *tracer = new QCPItemTracer(customPlot);
tracer->setGraph(customPlot->graph(0));
tracer->setInterpolating(true);
tracer->setVisible(false);
for (int i = 0; i < 4; i++){
tracer->setGraphKey(dates[i]);
tracer->updatePosition();
values.push_back(tracer->position->coords().y());
}
<强>结果:强>