15

新型肺炎感染人数数据图表化

 4 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzUxMTk4MzY3MA%3D%3D&%3Bmid=2247484308&%3Bidx=1&%3Bsn=d2cdad0cb0b225e2c54e821e763176e6
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

点击上方蓝字可直接关注!方便下次阅读。如果对你有帮助,可以点个在看,让它可以帮助到更多同志~

一、 概述

最近被新型肺炎搞得惶惶不可终日,眼看着人数一天天的攀升,直接看数据没有直观的感受,所以将数据图表化。

说做就做,以黑龙江省为例,我们在黑龙江省卫健委可以查看到每天的数据,如下:

M7namaZ.jpg!web

有了这些数据后,可以通过Qt的 QChart 模块将数据图表化,之前的文章举过条形图的示例。这次在之前的基础上使用折线图来体现。

Ok,接下来就是要将卫健委网页上的数据存起来,然后读取这些数据再绘制折线图。是直接存成文本文件还是存成 excel 呢?文本文件存储方便,但是进行数据解析以及个人阅读不方便;存成 excel 是我不会这个功能。。想了 3 秒钟,决定存成 excel 。于是在网上查找 Qt 如何读取 excel 数据,一顿操作猛如虎,资料就是无法用,而且还是 2016 年的资料,现在可是 0202 年了啊。发个牢骚而已,任务还是要完成的。又一顿操作,还真可以,而且不用下载其他软件,也无需使用第三方库,是一个 pri 工程。下面是如何操作了。

二、程序环境搭建

1. QtCharts 环境搭建

参考之前的文章 Qt 2D数据可视化之 QCharts

2. Qt 读取 excel cell 环境搭建

资源链接 https://github.com/QtExcel/QXlsx

下载解压后是下面这样:

1 是使用例子, 2pri 模块。

EBbMvaQ.png!web

1的运行效果如下

程序先是创建了一个Test.xlsx文件,然后读取 cell 11 列中的内容,控制台输出如下。如何包含 pri 模块可以参考 1 例子。

Bj6zEfQ.jpg!web

三、程序编写

1. Excel 数据如下

左上角第一个cell坐标为 (1, 1) ,使用的数据是图中框起来的确诊和新增确诊病例

reaqUf2.jpg!web

2. 导入.pri 及 charts 模块

include(../QXlsx/QXlsx.pri),可以参考例子中的

QT       += charts

3. 折线图的设置

过程可以参考之前的柱状图。

①设置折线相关属性

QLineSeries *m_confirmSeries;


m_confirmSeries = new QLineSeries();

m_confirmSeries->setName(tr("确诊")); //设置图例

m_confirmSeries->setPen(QPen(Qt::red, 3)); //设置线条宽度及颜色

②读取 xlsx 文件 cell 内容

Document xlsxR("E:\\MyQtProject\\2019nCov\\HLJ2019-nCov\\HLJ2019-nCov.xlsx");


if ( xlsxR.load() ) // 加载excel 文件

{

for(int i=0; i<10;i++)

{

int confirmRow = i + 7; int confirmCol = 3; //确诊人数

int increaseConfirmRow = i + 7; int increaseConfirmCol = 5; //新增确诊


Cell* confirmCell = xlsxR.cellAt(confirmRow, confirmCol); // 获得cell指针

Cell* increaseConfirmCell = xlsxR.cellAt(increaseConfirmRow, increaseConfirmCol);

if ( confirmCell != nullptr )

{

// read cell value (number(double), QDateTime, QString ...)

QVariant confirmVar = confirmCell->readValue();

QVariant increaseConfirmVar = increaseConfirmCell->readValue();

②~将cell内容填充到折线数据中

m_confirmSeries->append(i+1, confirmVar.toInt()); //为折线填充数据

m_increaseConfirmSeries->append(i+1, increaseConfirmVar.toInt());

}

else

{

qDebug() << "[debug] cell is not set.";

}

}

}

③将之前的折线添加到 QChart

QChart *chart = new QChart();

chart->addSeries(m_confirmSeries); //向chart添加折线图

chart->addSeries(m_increaseConfirmSeries);

chart->createDefaultAxes(); //创建默认坐标轴

chart->setTitle("2019-nCov");

将之前的 Chart 添加到 QChartView  

QChartView *chartView = new QChartView(chart); //将chart添加到View中

chartView->setRenderHint(QPainter::Antialiasing);//设置抗锯齿方式

最终效果如下:

横坐标是从25日开始,之后顺次加 1 天;纵坐标是人数

vmaMveJ.png!web

四、疫情总结

在家呆着别乱跑!

以史为鉴可以知兴替。

学不可以已!

如需完整工程可在公众号后台留言

欢迎大家关注公众号:

MZzeIjR.png!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK