Python實現(xiàn)疫情地圖可視化
一、 json模塊
JSON(JavaScript Object Notation)是一種輕量級的數(shù)據(jù)交換格式,易于閱讀和編寫,同時也易于機器解析和生成,并有效地提升網(wǎng)絡傳輸效率。
- json.loads():將json格式的str轉化成python的數(shù)據(jù)格式;
- json.loads():將python的數(shù)據(jù)格式(字典或列表)轉化成json格式;
# 如何將json數(shù)據(jù)解析成我們所熟悉的Python數(shù)據(jù)類型?
import json
# 將json格式的str轉化成python的數(shù)據(jù)格式:字典
dic = json.loads('{"name":"Tom","age":23}')
res = json.loads('["name","age","gender"]')
print(f'利用loads將json字符串轉化成Python數(shù)據(jù)類型{dic}',type(dic))
print(f'利用loads將json字符串轉化成Python數(shù)據(jù)類型{res}',type(res))

dics = {"name":"Tom","age":23}
result = json.dumps(dics)
print(type(result))
result

二、通過Python實現(xiàn)疫情地圖可視化
需求:爬取疫情的數(shù)據(jù)、如何處理json數(shù)據(jù)以及根據(jù)疫情數(shù)據(jù)如何利用pyecharts繪制疫情地圖。


1.數(shù)據(jù)的獲取(基于request模塊)
import requests
import json
# 國內疫情數(shù)據(jù)
China_url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'
headers = {
# 瀏覽器偽裝
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',
'referer': 'https://news.qq.com/',
}
# 發(fā)起get請求,獲取響應數(shù)據(jù)
response = requests.get(China_url,headers=headers).json()
data = json.loads(response['data'])
# 保存數(shù)據(jù)
with open('./2021-02-03國內疫情.json','w',encoding='utf-8') as f:
# 不采用ASCII編碼
f.write(json.dumps(data,ensure_ascii=False,indent=2))
爬取的數(shù)據(jù)保存格式為json,開頭的部分數(shù)據(jù)如下:

2.將json格式的數(shù)據(jù)保存到Excel
無論是json數(shù)據(jù)存儲的,還是Python的基本數(shù)據(jù)類型存儲的,對于數(shù)據(jù)分析都不是很友好,所以我們可以將其數(shù)據(jù)存儲類型轉化為pandas的DataFrame類型,因為DataFrame和Excel可以更好的相互轉換。
生成的數(shù)據(jù)模式如下:

將以上的數(shù)據(jù)進行處理,獲得Excel表一樣規(guī)范的數(shù)據(jù)格式。
import pandas as pd
chinaTotalData = pd.DataFrame(china_citylist)
# 將整體數(shù)據(jù)chinaTotalData中的today和total數(shù)據(jù)添加到DataFrame中
# 處理total字典里面的各個數(shù)據(jù)項
# ======================================================================
confirmlist = []
suspectlist = []
deadlist = []
heallist = []
deadRatelist = []
healRatelist = []
# print(chinaTotalData['total'].values.tolist()[0])
for value in chinaTotalData['total'].values.tolist():
confirmlist.append(value['confirm'])
suspectlist.append(value['suspect'])
deadlist.append(value['dead'])
heallist.append(value['heal'])
deadRatelist.append(value['deadRate'])
healRatelist.append(value['healRate'])
chinaTotalData['confirm'] = confirmlist
chinaTotalData['suspect'] = suspectlist
chinaTotalData['dead'] = deadlist
chinaTotalData['heal'] = heallist
chinaTotalData['deadRate'] = deadRatelist
chinaTotalData['healRate'] = healRatelist
# ===================================================================
# 創(chuàng)建全國today數(shù)據(jù)
today_confirmlist = []
today_confirmCutslist = []
for value in chinaTotalData['today'].values.tolist():
today_confirmlist.append(value['confirm'])
today_confirmCutslist.append(value['confirmCuts'])
chinaTotalData['today_confirm'] = today_confirmlist
chinaTotalData['today_confirmCuts'] = today_confirmCutslist
# ==================================================================
# 刪除total、today兩列
chinaTotalData.drop(['total','today'],axis=1,inplace=True)
chinaTotalData.head()
# 將其保存到Excel中
chinaTotalData.to_excel('2021-02-03國內疫情.xlsx',index=False)
處理好的數(shù)據(jù)結構如下表:

3.應用pyecharts進行數(shù)據(jù)可視化
pyecharts是一款將python與echarts結合的強大的數(shù)據(jù)可視化工具。繪制出來的圖比Python的Matplotlib簡單美觀。使用之前需要在Python環(huán)境中按照pycharts。在終端中輸入命令:pip install pyecharts
利用pyecharts繪制疫情地圖
根據(jù)上面的疫情數(shù)據(jù),我們可以利用其畫出全國的疫情地圖
在繪制前,我們需要安裝echarts的地圖包(可根據(jù)不同的地圖需求進行安裝)
pip install echarts-countries-pypkg pip install echarts-china-provinces-pypkg pip install echarts-china-cities-pypkg pip install echarts-china-misc-pypkg pip install echarts-china-countries-pypkg pip install echarts-united-kingdom-pypkg
# 導入對應的繪圖工具包
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Map
df = pd.read_excel('./2021-02-03國內疫情.xlsx')
# 1.根據(jù)繪制國內總疫情圖(確診)
data = df.groupby(by='province',as_index=False).sum()
data_list = list(zip(data['province'].values.tolist(),data['confirm'].values.tolist()))
# 數(shù)據(jù)格式[(黑龍江,200),(吉林,300),...]
def map_china() -> Map:
c = (
Map()
.add(series_name="確診病例",data_pair=data_list,maptype='china')
.set_global_opts(
title_opts = opts.TitleOpts(title='疫情地圖'),
visualmap_opts=opts.VisualMapOpts(is_piecewise=True,
pieces = [{"max":9, "min":0, "label":"0-9","color":"#FFE4E1"},
{"max":99, "min":10, "label":"10-99","color":"#FF7F50"},
{"max":499, "min":100, "label":"100-4999","color":"#F08080"},
{"max":999, "min":500, "label":"500-999","color":"#CD5C5C"},
{"max":9999, "min":1000, "label":"1000-9999","color":"#990000"},
{"max":99999, "min":10000, "label":"10000-99999","color":"#660000"},]
)
)
)
return c
d_map = map_china()
d_map.render("mapEchrts.html")
最終的運行效果如下:

注:以上的運行環(huán)境是Python3.7版本,IDE是基于瀏覽器端的Jupter Notebook。
以上就是Python實現(xiàn)疫情地圖可視化的詳細內容,更多關于python 疫情地圖可視化的資料請關注腳本之家其它相關文章!
相關文章
Python全棧之文件函數(shù)和函數(shù)參數(shù)
這篇文章主要為大家介紹了Python的文件函數(shù)和函數(shù)參數(shù),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2021-12-12
Python中numpy的np.percentile百分位函數(shù)舉例詳解
在python中計算一個多維數(shù)組的任意百分比分位數(shù),此處的百分位是從小到大排列,只需用np.percentile即可,這篇文章主要給大家介紹了關于Python中numpy的np.percentile百分位函數(shù)的相關資料,需要的朋友可以參考下2024-08-08
python網(wǎng)絡爬蟲之如何偽裝逃過反爬蟲程序的方法
本篇文章主要介紹了python網(wǎng)絡爬蟲之如何偽裝逃過反爬蟲程序的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
Python中的 ansible 動態(tài)Inventory 腳本
這篇文章主要介紹了Python中的 ansible 動態(tài)Inventory 腳本,本章節(jié)通過實例代碼從mysql數(shù)據(jù)作為數(shù)據(jù)源生成動態(tài)ansible主機為入口介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2020-01-01

