qcustomplot 2.1.1版本 绘制瀑布图水平流动实例
时间: 2023-12-14 18:03:18 浏览: 62
以下是一个使用QCustomPlot库绘制水平流动的瀑布图的示例代码:
```cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qcustomplot.h"
#include <QTimer>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 创建QCustomPlot对象
customPlot = new QCustomPlot(this);
// 设置标题
customPlot->plotLayout()->insertRow(0);
customPlot->plotLayout()->addElement(0, 0, new QCPTextElement(customPlot, "Horizontal Waterfall Plot", QFont("sans", 12, QFont::Bold)));
// 创建QCPColorMap对象
colorMap = new QCPColorMap(customPlot->xAxis, customPlot->yAxis);
// 设置数据范围
colorMap->setDataRange(QCPRange(0, 10), QCPRange(0, 100));
// 设置颜色映射
QCPColorGradient colorGradient;
colorGradient.setColorStopAt(0, QColor(255, 0, 0));
colorGradient.setColorStopAt(0.5, QColor(255, 255, 255));
colorGradient.setColorStopAt(1, QColor(0, 0, 255));
colorMap->setGradient(colorGradient);
// 设置数据
QVector<double> xData(11), yData(101), zData(11 * 101);
for (int i = 0; i < 11; ++i) {
xData[i] = i;
for (int j = 0; j < 101; ++j) {
yData[j] = j;
zData[i * 101 + j] = qSin(i / 2.0) * qSin(j / 10.0);
}
}
colorMap->setData(xData, yData, zData);
// 创建QCPColorScale对象
colorScale = new QCPColorScale(customPlot);
customPlot->plotLayout()->addElement(0, 1, colorScale);
// 设置颜色刻度
colorScale->setType(QCPAxis::atRight);
colorMap->setColorScale(colorScale);
// 设置自动调整坐标轴范围
customPlot->rescaleAxes();
// 设置坐标轴范围
customPlot->xAxis->setRange(0, 10);
customPlot->yAxis->setRange(0, 100);
// 创建QCPColorMapData对象
data = colorMap->data();
// 设置QCPColorMapData对象的行顺序
data->setInterpolate(true);
data->setTightBoundary(false);
data->setRangeReversed(false);
data->setKeyRange(QCPRange(0, 10));
data->setValueRange(QCPRange(0, 100));
data->setSize(11, 101);
// 设置QCPColorMapData对象的列顺序
for (int i = 0; i < 11; ++i) {
for (int j = 0; j < 101; ++j) {
data->setCell(i, j, zData[i * 101 + j]);
}
}
// 设置QCPColorMapData对象的颜色映射
data->setGradient(colorGradient);
// 设置画布
customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
customPlot->setNoAntialiasingOnDrag(true);
customPlot->setNotAntialiasedElement(QCP::aeAll);
// 添加QCustomPlot对象到主窗口
setCentralWidget(customPlot);
// 开始动画效果
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateWaterfall()));
timer->start(50);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::updateWaterfall()
{
// 移动数据
for (int i = 0; i < 11; ++i) {
for (int j = 0; j < 100; ++j) {
data->setCell(i, j, data->cell(i, j + 1));
}
}
for (int i = 0; i < 11; ++i) {
data->setCell(i, 100, qSin(i / 2.0) * qSin((100 + 1) / 10.0));
}
// 重绘
customPlot->replot();
}
```
这个示例代码创建了一个水平流动的瀑布图,并使用一个定时器来更新数据,让瀑布图动起来。希望这个示例代码对您有所帮助!
阅读全文