Python 製做全國疫情地圖

製做全國疫情地圖


開篇說明: 本篇內容僅作我的學習使用。python

疫情期間,但願你們注意我的防禦。中國加油!json

獲取數據


使用工具

爬取工具: requestssegmentfault

瀏覽器: Google Chrome瀏覽器

requests 是 Python 第三方庫,可用做爬取數據。詳細的內容可參考官方文檔(本篇幅先不展開介紹):bash

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

使用以前,須要先安裝 requests:數據結構

pip install requests

若是是直接安裝 Anaconda 的話,這一步能夠省略。echarts

數據源

這裏使用的是騰訊的數據源,騰訊提供的疫情數據直接輸出在 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()

效果展現:

效果展現


以上就是本篇的主要內容

歡迎關注微信公衆號《書所集錄》
相關文章
相關標籤/搜索