Python 制作全国疫情地图

制作全国疫情地图


开篇说明: 本篇内容仅做个人学习使用。

疫情期间,希望大家注意个人防护。中国加油!

获取数据


使用工具

爬取工具: requests

浏览器: Google Chrome

requests 是 Python 第三方库,可用作爬取数据。详细的内容可参考官方文档(本篇幅先不展开介绍):

https://requests.readthedocs.io/en/master/

使用之前,需要先安装 requests:

pip install requests

如果是直接安装 Anaconda 的话,这一步可以省略。

数据源

这里使用的是腾讯的数据源,腾讯提供的疫情数据直接输出在 console 上,非常的友好。

具体地址:https://news.qq.com/zt2020/page/feiyan.htm

打开上面的链接,按 F12 或者右键点击选择“检查”,在调出的开发者工具上方选项卡中选择 Console。

console

这里可以看到全部的数据都在这里,其中 lastUpdateTime 是最后更新时间,chinaTotal 是现在疫情总体的情况(包括确诊数,疑似数,死亡数,治愈数),areaTree 里面包含详细的信息。

areaTree

这里,只要我们中国的详细数据,这些数据就包含在 areaTree 索引为 0 下面的 children 中。

通过上面的观察,我们已经知道需要获取的数据结构是怎样的。现在跳转到输出这些数据的 intro_vp.js 脚本中,查看数据是如何得到的。

get_data

图中标记的部分就是获取数据的接口,现在我们使用 requests 库来获取接口返回的数据。

获取数据

直接看代码:

import requests
import json

# 数据接口
url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'
# 读取数据转换为 JSON 格式
data = json.loads(requests.get(url).json()['data'])
# 更新时间
update_time = data['lastUpdateTime']
# 全国数据
china_total = data['chinaTotal']
# 全国各地具体数据
China = data['areaTree'][0]['children']

# 将数据生成为副标题
ncp_info = '确诊:{} 疑似:{} 死亡:{} 治愈:{} 更新日期:{}'.format(
    china_total['confirm'],
    china_total['suspect'],
    china_total['dead'],
    china_total['heal'],
    update_time
    )

绘制地图


地图绘制部分,Basemap 虽然能够绘制地图,但是使用比较麻烦。这里推荐使用 pyecharts 库。

pyecharts 是一个用于生产 Echarts 图表的类库,Echarts 是百度开源的一个数据可视化 JS 库。

使用之前先安装库:

pip install pyecharts

这里安装的时候可能会出现超时。遇到这种情况的时候,可以考虑使用清华镜像:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyecharts

安装地图文件

全球国家地图: echarts-countries-pypkg

中国省级地图: echarts-china-provinces-pypkg

中国市级地图: echarts-china-cities-pypkg

pip install echarts-countries-pypkg
pip install echarts-china-provinces-pypkg
pip install echarts-china-cities-pypkg

关于 pyecharts 的内容也可以参考下面的文档:

https://pyecharts.org/#/zh-cn/intro

前面已经获取到数据,现在使用 pyecharts 绘制地图。

首先导入所需的库

from pyecharts.charts import Map, Geo
from pyecharts import options as opts
from pyecharts.globals import GeoType

配置 Geo,并保存:

c = (
    Geo()
    .add_schema(
        maptype='china',
        # 设置地图区域颜色
        itemstyle_opts=opts.ItemStyleOpts(color="#323c48", border_color="#111"),
    )
    .add(
        'geo',
        # 序列数据,添加省会名称以及确诊数量
        [list([China[i]['name'], China[i]['total']['confirm']]) for i in range(len(China))],
        # 设置涟漪效果
        type_=GeoType.EFFECT_SCATTER,
    )
    .set_series_opts(
        # 不显示 Label
        label_opts=opts.LabelOpts(is_show=False),
    )
    .set_global_opts(
        # 设置标题,副标题,放置中间
        title_opts=opts.TitleOpts(title="全国疫情地图", subtitle=ncp_info, pos_left='center'),
        # 设置渐变,最大值设为 平均值
        visualmap_opts=opts.VisualMapOpts(min_=0, max_=china_total['confirm']/len(data)),
        # 不显示图例
        legend_opts=opts.LegendOpts(is_show=False)
    )
)

# 保存地图
c.render()

效果展示:

效果展示


以上就是本篇的主要内容


发布了82 篇原创文章 · 获赞 43 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_45642918/article/details/104348420
今日推荐