QT Chart 散点图绘制:
提示:pro工程文件 + charts
头文件:
#include <QtCharts/QScatterSeries>
#include <QtCharts/QLegendMarker>
#include <QtCharts/QChartView>
#include
#include
//命名空间
QT_CHARTS_USE_NAMESPACE
主要代码:
QCategoryAxis *axisX=new QCategoryAxis;axisX->setMin(-5);//设置坐标轴显示范围axisX->setMax(55);//![0]append要按照大小顺序依次添加//! 每一个append就是一条坐标轴axisX->append(("8元畅享套餐"),0);axisX->append(("58元个人套餐"),10);axisX->append(("78元个人套餐"),20);axisX->append(("98元家庭套餐"),30);axisX->append(("128元家庭套餐"),40);axisX->append(("198元家庭套餐"),50);QScatterSeries *series0 = new QScatterSeries();series0->setName(("在网用户"));series0->setMarkerShape(QScatterSeries::MarkerShapeCircle);//设置散点图标类型,QT只自带了正方形和远点,当然也自定义图片使用series0->setMarkerSize(20.0); //设置散点图标大小QScatterSeries *series1 = new QScatterSeries();series1->setName(("欠费用户"));series1->setMarkerShape(QScatterSeries::MarkerShapeCircle);series1->setMarkerSize(20.0);QScatterSeries *series2 = new QScatterSeries();series2->setName(("停机用户"));series2->setMarkerShape(QScatterSeries::MarkerShapeCircle);series2->setMarkerSize(20.0);QScatterSeries *series3 = new QScatterSeries();series3->setName(("注销用户"));series3->setMarkerShape(QScatterSeries::MarkerShapeCircle);series3->setMarkerSize(20.0);//添加serise数据方式1series0->append(0, 0);series0->append(15, 4);series0->append(33, 8);series0->append(47, 4);series0->append(56, 12);//添加serise数据方式2,等效于上面append*series1 << QPointF(25, 2) << QPointF(34, 3) << QPointF(14, 6) << QPointF(48, 3) << QPointF(50, 2);*series2 << QPointF(16, 5) << QPointF(33, 6) << QPointF(26, 3) << QPointF(19, 5);*series3 << QPointF(54, 5) << QPointF(28, 3) << QPointF(27, 5) << QPointF(46, 8);QChartView *chartView = new QChartView(ui->widget); //主动界面,可以添加父界面关闭时无需手动释放内存空间 ui->widget是拖到MainWidget上的界面chartView->setRenderHint(QPainter::Antialiasing);chartView->chart()->addSeries(series0);chartView->chart()->addSeries(series1);chartView->chart()->addSeries(series2);chartView->chart()->addSeries(series3);chartView->chart()->setTitle(("套餐价格对用户忠诚度的影响"));chartView->chart()->createDefaultAxes(); //自动生成坐标轴chartView->chart()->setAxisX(axisX,series0); //替换生成的x轴坐标,前提条件是已经自动生成坐标轴chartView->chart()->setAxisX(axisX,series1); //让series数据与坐标轴对应chartView->chart()->setAxisX(axisX,series2);chartView->chart()->setAxisX(axisX,series3);//![1]单独添加坐标轴,如果自动生成了坐标轴会被替换或叠加(放在自动生成坐标轴前会被替换,放在自动生成坐标轴后会叠加在一起)//! chartView->chart()->addAxis(axisX,Qt::AlignBottom);chartView->chart()->setDropShadowEnabled(false);chartView->chart()->legend()->setMarkerShape(QLegend::MarkerShapeFromSeries);chartView->resize(1051,571);chartView->show();//释放内存空间axisX->destroyed();series0->destroyed();series1->destroyed();series2->destroyed();series3->destroyed();
网上Qt Chart的文章都是QT模板里面的,索性自己写了一个
下载链接(https://www.aliyundrive.com/s/51kpdi3dTLU)