好久没有更新了,把最近学习到的东西做一个简单的总结
一、qcustomplot是什么
在没有接触qt之前,各种奇怪的图到底怎么画出来的还是觉得很厉害的,但是当你拥有了qcustomplot,你就拥有了整个世界!可以说qcustomplot算是促进我更快学习前辈们的代码了!
简单说来qcustomplot其实就是个头文件,大家把他加入自己的项目之后,就可以画出折线图、柱状图、热力图等等等。
二、实例
1.画出一个抛物线
QVector<double> x(101), y(101); //初始化向量x和y
for (int i=0; i<101; ++i)
{
x[i] = i/50.0 - 1; // x范围[-1,1]
y[i] = x[i]*x[i]; // y=x*x
}
ui->customPlot->addGraph();//添加数据曲线(一个图像可以有多个数据曲线)
// graph(0);可以获取某个数据曲线(按添加先后排序)
// setData();为数据曲线关联数据
ui->customPlot->graph(0)->setData(x, y);
ui->customPlot->graph(0)->setName("第一个示例");// 设置图例名称
// 为坐标轴添加标签
ui->customPlot->xAxis->setLabel("x");
ui->customPlot->yAxis->setLabel("y");
// 设置坐标轴的范围,以看到所有数据
ui->customPlot->xAxis->setRange(-1, 1);
ui->customPlot->yAxis->setRange(0, 1);
ui->customPlot->legend->setVisible(true); // 显示图例
// 重画图像
ui->customPlot->replot();
2.在一张图上绘制多条曲线
官方代码如下
QCustomPlot *customPlot = ui->customPlot;//创建customPlot
//每条曲线都会独占一个graph()
customPlot->addGraph();
customPlot->graph(0)->setPen(QPen(Qt::blue)); // 曲线的颜色
customPlot->graph(0)->setBrush(QBrush(QColor(0, 0, 255, 20))); // 曲线与X轴包围区的颜色
customPlot->addGraph();//添加graph等价于添加一条新曲线
customPlot->graph(1)->setPen(QPen(Qt::red)); // 曲线的颜色
// 生成模拟数据点 (x-y0 第一条曲线, x-y1为第2条曲线):
QVector<double> x(251), y0(251), y1(251);
for (int i=0; i<251; ++i)
{
x[i] = i;
y0[i] = qExp(-i/150.0)*qCos(i/10.0); // 第一条曲线:y0衰减cos
y1[i] = qExp(-i/150.0); // 第二条曲线:y1衰减指数
}
// 边框右侧和上侧均显示刻度线,但不显示刻度值:
customPlot->xAxis2->setVisible(true);
customPlot->xAxis2->setTickLabels(false);
customPlot->yAxis2->setVisible(true);
customPlot->yAxis2->setTickLabels(false);
// 使上下两个X轴的范围总是相等,使左右两个Y轴的范围总是相等
connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));
// 把已存在的数据填充进graph的数据区
customPlot->graph(0)->setData(x, y0);
customPlot->graph(1)->setData(x, y1);
//自动调整XY轴的范围,以便显示出graph(0)中所有的点(下面会单独讲到这个函数)
customPlot->graph(0)->rescaleAxes();
//自动调整XY轴的范围,以便显示出graph(1)中所有的点
customPlot->graph(1)->rescaleAxes(true);
// 支持鼠标拖拽轴的范围、滚动缩放轴的范围,左键点选图层(每条曲线独占一个图层)
customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
// 立即刷新图像
ui->customPlot->replot();
小tips:
1.每条曲线都是一个单独的graph,新建graph通过customPlot->addGraph()实现;
2.每一个QCustomPlot都有上下左右四个坐标轴,分别是customPlot->xAxis2(上)、xAxis(下)、yAxis(左)、yAxis2(右)
3.每个轴都可以单独显示、是否显示刻度、几个刻度、刻度的值是否显示
4.如果想将多条曲线的x轴和y轴范围全部显示出来,需要用到“自动缩放轴的范围”函数:
rescaleAxes( bool onlyEnlarge = false),该函数的作用是,使当前plot的XY的显示范围恰好(不能大也不能小)容纳本曲线,如果plot中有多条曲线,我们依次执行
3.绘制热力图
锵锵!这才是今天的重点!学习了很久的热力图,再整理一下放下一期发哈哈哈哈