Python實現疫情地圖可視化
JSON(JavaScript Object Notation)是一種輕量級的數據交換格式,易于閱讀和編寫,同時也易于機器解析和生成,并有效地提升網絡傳輸效率。
json.loads():將json格式的str轉化成python的數據格式; json.loads():將python的數據格式(字典或列表)轉化成json格式;# 如何將json數據解析成我們所熟悉的Python數據類型?import json# 將json格式的str轉化成python的數據格式:字典dic = json.loads(’{'name':'Tom','age':23}’)res = json.loads(’['name','age','gender']’)print(f’利用loads將json字符串轉化成Python數據類型{dic}’,type(dic))print(f’利用loads將json字符串轉化成Python數據類型{res}’,type(res))
dics = {'name':'Tom','age':23}result = json.dumps(dics)print(type(result))result
需求:爬取疫情的數據、如何處理json數據以及根據疫情數據如何利用pyecharts繪制疫情地圖。
import requestsimport json# 國內疫情數據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/’,}# 發起get請求,獲取響應數據response = requests.get(China_url,headers=headers).json()data = json.loads(response[’data’])# 保存數據with open(’./2021-02-03國內疫情.json’,’w’,encoding=’utf-8’) as f: # 不采用ASCII編碼 f.write(json.dumps(data,ensure_ascii=False,indent=2))
爬取的數據保存格式為json,開頭的部分數據如下:
無論是json數據存儲的,還是Python的基本數據類型存儲的,對于數據分析都不是很友好,所以我們可以將其數據存儲類型轉化為pandas的DataFrame類型,因為DataFrame和Excel可以更好的相互轉換。
生成的數據模式如下:
將以上的數據進行處理,獲得Excel表一樣規范的數據格式。
import pandas as pdchinaTotalData = pd.DataFrame(china_citylist)# 將整體數據chinaTotalData中的today和total數據添加到DataFrame中# 處理total字典里面的各個數據項# ======================================================================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’] = confirmlistchinaTotalData[’suspect’] = suspectlistchinaTotalData[’dead’] = deadlistchinaTotalData[’heal’] = heallistchinaTotalData[’deadRate’] = deadRatelistchinaTotalData[’healRate’] = healRatelist# ===================================================================# 創建全國today數據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_confirmlistchinaTotalData[’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)
處理好的數據結構如下表:
pyecharts是一款將python與echarts結合的強大的數據可視化工具。繪制出來的圖比Python的Matplotlib簡單美觀。使用之前需要在Python環境中按照pycharts。在終端中輸入命令:pip install pyecharts
利用pyecharts繪制疫情地圖根據上面的疫情數據,我們可以利用其畫出全國的疫情地圖在繪制前,我們需要安裝echarts的地圖包(可根據不同的地圖需求進行安裝)
pip install echarts-countries-pypkgpip install echarts-china-provinces-pypkgpip install echarts-china-cities-pypkgpip install echarts-china-misc-pypkgpip install echarts-china-countries-pypkgpip install echarts-united-kingdom-pypkg
# 導入對應的繪圖工具包import pandas as pdfrom pyecharts import options as optsfrom pyecharts.charts import Mapdf = pd.read_excel(’./2021-02-03國內疫情.xlsx’)# 1.根據繪制國內總疫情圖(確診)data = df.groupby(by=’province’,as_index=False).sum()data_list = list(zip(data[’province’].values.tolist(),data[’confirm’].values.tolist()))# 數據格式[(黑龍江,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 cd_map = map_china()d_map.render('mapEchrts.html')
最終的運行效果如下:
注:以上的運行環境是Python3.7版本,IDE是基于瀏覽器端的Jupter Notebook。
以上就是Python實現疫情地圖可視化的詳細內容,更多關于python 疫情地圖可視化的資料請關注好吧啦網其它相關文章!
相關文章:
