网易首页 > 网易号 > 正文 申请入驻

Python实战抓肺炎疫情实时数据,画2019-nCoV疫情地图

0
分享至

近期,于武汉发现的新型冠状病毒已经蔓延至全国地区,并且各地区的确诊人数正在不断上升,其传播范围和发展趋势成为了人们每日关注的焦点。


为了形象准确地展现疫情发展状况,各大媒体和网络平台纷纷采用疫情地图进行统计数据的可视化,利用python画武汉肺炎疫情地图。先前并没有关注武汉肺炎的具体数据,也没有画过类似的数据分布图。下面我们一起来看一下吧。

首先搜到的是腾讯的疫情实时追踪,那就用这个数据源吧,

数据地址:https://news.qq.com/zt2020/page/feiyan.htm?from=timeline&isappinstalled=0

有了网址怎么抓数据呢?这里给大家一给最简便找到最靠谱的下载方式,用FireFox浏览器,下面的讲解就以FireFox为例(其他浏览器基本类似)。

打开菜单,点击“Web开发者”,在递进菜单中选择"网络":

刷新页面,我们很快就能发现,应答类型为json格式的这个请求,最有可能包含我们需要的数据了:

深入分析,我们就得到了url地址、请求方法、参数、应答格式等信息。查询参数中,callback是回调函数名,我们可以尝试置空,_应该是以毫秒为单位的当前时间戳。有了这些信息,分分钟就可以抓到数据了。我们先在IDLE中以交互方式抓一下看看效果:

>>> import time, json, requests

>>> url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=&_=%d'%int(time.time()*1000)

>>> data = json.loads(requests.get(url=url).json()['data'])

只要两行代码,就可以抓到数据了。怎么样,是不是超级简单?我们在来看看数据结构:

>>> data.keys()

dict_keys(['chinaTotal', 'chinaAdd', 'lastUpdateTime', 'areaTree', 'chinaDayList', 'chinaDayAddList', 'isShowAdd'])

>>> d = data['areaTree'][0]['children']

>>> len(d)

34

>>> [item['name'] for item in d]

['湖北', '浙江', '广东', '河南', '湖南', '江西', '安徽', '重庆', '山东', '江苏', '四川', '上海', '北京', '福建', '黑龙江', '广西', '陕西', '河北', '云南', '海南', '山西', '辽宁', '天津', '贵州', '甘肃', '吉林', '内蒙古', '宁夏', '新疆', '香港', '青海', '台湾', '澳门', '西藏']

>>> d[0]['children']

[{'name': '武汉', 'total': {'confirm': 10117, 'suspect': 0, 'dead': 414, 'heal': 431}, 'today': {'confirm': 1766, 'suspect': 0, 'dead': 52, 'heal': 58}}, {'name': '孝感', 'total': {'confirm': 1886, 'suspect': 0, 'dead': 25, 'heal': 9}, 'today': {'confirm': 424, 'suspect': 0, 'dead': 7, 'heal': 3}}, {'name': '黄冈', 'total': {'confirm': 1807, 'suspect': 0, 'dead': 29, 'heal': 60}, 'today': {'confirm': 162, 'suspect': 0, 'dead': 4, 'heal': 8}}, {'name': '随州', 'total': {'confirm': 834, 'suspect': 0, 'dead': 9, 'heal': 9}, 'today': {'confirm': 128, 'suspect': 0, 'dead': 1, 'heal': 0}}, {'name': '荆州', 'total': {'confirm': 801, 'suspect': 0, 'dead': 10, 'heal': 18}, 'today': {'confirm': 88, 'suspect': 0, 'dead': 1, 'heal': 6}}, {'name': '襄阳', 'total': {'confirm': 787, 'suspect': 0, 'dead': 2, 'heal': 10}, 'today': {'confirm': 52, 'suspect': 0, 'dead': 0, 'heal': 3}}, {'name': '黄石', 'total': {'confirm': 566, 'suspect': 0, 'dead': 2, 'heal': 25}, 'today': {'confirm': 57, 'suspect': 0, 'dead': 0, 'heal': 7}}, {'name': '宜昌', 'total': {'confirm': 563, 'suspect': 0, 'dead': 6, 'heal': 9}, 'today': {'confirm': 67, 'suspect': 0, 'dead': 2, 'heal': 0}}, {'name': '荆门', 'total': {'confirm': 508, 'suspect': 0, 'dead': 17, 'heal': 21}, 'today': {'confirm': 86, 'suspect': 0, 'dead': 1, 'heal': 5}}, {'name': '鄂州', 'total': {'confirm': 423, 'suspect': 0, 'dead': 18, 'heal': 8}, 'today': {'confirm': 41, 'suspect': 0, 'dead': 0, 'heal': 2}}, {'name': '咸宁', 'total': {'confirm': 399, 'suspect': 0, 'dead': 1, 'heal': 3}, 'today': {'confirm': 15, 'suspect': 0, 'dead': 1, 'heal': 1}}, {'name': '十堰', 'total': {'confirm': 353, 'suspect': 0, 'dead': 0, 'heal': 14}, 'today': {'confirm': 35, 'suspect': 0, 'dead': 0, 'heal': 5}}, {'name': '仙桃', 'total': {'confirm': 265, 'suspect': 0, 'dead': 5, 'heal': 0}, 'today': {'confirm': 40, 'suspect': 0, 'dead': 1, 'heal': 0}}, {'name': '恩施州', 'total': {'confirm': 144, 'suspect': 0, 'dead': 0, 'heal': 10}, 'today': {'confirm': 6, 'suspect': 0, 'dead': 0, 'heal': 4}}, {'name': '天门', 'total': {'confirm': 138, 'suspect': 0, 'dead': 10, 'heal': 1}, 'today': {'confirm': 10, 'suspect': 0, 'dead': 0, 'heal': 1}}, {'name': '潜江', 'total': {'confirm': 64, 'suspect': 0, 'dead': 1, 'heal': 0}, 'today': {'confirm': 10, 'suspect': 0, 'dead': 0, 'heal': 0}}, {'name': '神农架', 'total': {'confirm': 10, 'suspect': 0, 'dead': 0, 'heal': 2}, 'today': {'confirm': 0, 'suspect': 0, 'dead': 0, 'heal': 0}}, {'name': '地区待确认', 'total': {'confirm': 0, 'suspect': 0, 'dead': 0, 'heal': 3}, 'today': {'confirm': 0, 'suspect': 0, 'dead': 0, 'heal': 0}}]

2

以省为单位画疫情图,我们只需要统计同属一个省的所有地市的确诊数据即可。最终的数据抓取代码如下:

import time, json, requests

def catch_distribution():

"""抓取行政区域确诊分布数据"""

data = {}

url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=&_=%d'%int(time.time()*1000)

for item in json.loads(requests.get(url=url).json()['data'])['areaTree'][0]['children']:

if item['name'] not in data:

data.update({item['name']:0})

for city_data in item['children']:

data[item['name']] += int(city_data['total']['confirm'])

return data

3

数据可视化,我习惯使用matplotlib模块。matplotlib有很多扩展工具包(toolkits),比如,画3D需要mplot3d工具包,画地图的话,则需要basemap工具包,以及处理地图投影的pyproj模块。另外画海陆分界线、国界线、行政分界线等还需要shape数据。所需模块请自行安装,shape文件可以从这里下载,绘图用到的矢量字库可以从自己的电脑上随便找一个(我用的是simsun.ttf)。我的主程序是2019nCoV.py,shape文件下载下来之后,是这样保存的:

以下为全部代码,除了疫情地图,还包括了全国每日武汉肺炎确诊数据的下载和可视化。

# -*- coding: utf-8 -*-

import time

import json

import requests

from datetime import datetime

import numpy as np

import matplotlib

import matplotlib.figure

from matplotlib.font_manager import FontProperties

from matplotlib.backends.backend_agg import FigureCanvasAgg

from matplotlib.patches import Polygon

from matplotlib.collections import PatchCollection

from mpl_toolkits.basemap import Basemap

import matplotlib.pyplot as plt

import matplotlib.dates as mdates

plt.rcParams['font.sans-serif'] = ['FangSong'] # 设置默认字体

plt.rcParams['axes.unicode_minus'] = False # 解决保存图像时'-'显示为方块的问题

def catch_daily():

"""抓取每日确诊和死亡数据"""

url = 'https://view.inews.qq.com/g2/getOnsInfo?name=wuwei_ww_cn_day_counts&callback=&_=%d'%int(time.time()*1000)

data = json.loads(requests.get(url=url).json()['data'])

data.sort(key=lambda x:x['date'])

date_list = list() # 日期

confirm_list = list() # 确诊

suspect_list = list() # 疑似

dead_list = list() # 死亡

heal_list = list() # 治愈

for item in data:

month, day = item['date'].split('/')

date_list.append(datetime.strptime('2020-%s-%s'%(month, day), '%Y-%m-%d'))

confirm_list.append(int(item['confirm']))

suspect_list.append(int(item['suspect']))

dead_list.append(int(item['dead']))

heal_list.append(int(item['heal']))

return date_list, confirm_list, suspect_list, dead_list, heal_list

def catch_distribution():

"""抓取行政区域确诊分布数据"""

data = {}

url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=&_=%d'%int(time.time()*1000)

for item in json.loads(requests.get(url=url).json()['data'])['areaTree'][0]['children']:

if item['name'] not in data:

data.update({item['name']:0})

for city_data in item['children']:

data[item['name']] += int(city_data['total']['confirm'])

return data

def plot_daily():

"""绘制每日确诊和死亡数据"""

date_list, confirm_list, suspect_list, dead_list, heal_list = catch_daily() # 获取数据

plt.figure('2019-nCoV疫情统计图表', facecolor='#f4f4f4', figsize=(10, 8))

plt.title('2019-nCoV疫情曲线', fontsize=20)

plt.plot(date_list, confirm_list, label='确诊')

plt.plot(date_list, suspect_list, label='疑似')

plt.plot(date_list, dead_list, label='死亡')

plt.plot(date_list, heal_list, label='治愈')

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m-%d')) # 格式化时间轴标注

plt.gcf().autofmt_xdate() # 优化标注(自动倾斜)

plt.grid(linestyle=':') # 显示网格

plt.legend(loc='best') # 显示图例

plt.savefig('2019-nCoV疫情曲线.png') # 保存为文件

#plt.show()

def plot_distribution():

"""绘制行政区域确诊分布数据"""

data = catch_distribution()

font_14 = FontProperties(fname='res/simsun.ttf', size=14)

font_11 = FontProperties(fname='res/simsun.ttf', size=11)

lat_min = 0

lat_max = 60

lon_min = 77

lon_max = 140

handles = [

matplotlib.patches.Patch(color='#ffaa85', alpha=1, linewidth=0),

matplotlib.patches.Patch(color='#ff7b69', alpha=1, linewidth=0),

matplotlib.patches.Patch(color='#bf2121', alpha=1, linewidth=0),

matplotlib.patches.Patch(color='#7f1818', alpha=1, linewidth=0),

]

labels = [ '1-9人', '10-99人', '100-999人', '>1000人']

provincePos = {

"辽宁省":[121.7,40.9],

"吉林省":[124.5,43.5],

"黑龙江省":[125.6,46.5],

"北京市":[116.0,39.9],

"天津市":[117.0,38.7],

"内蒙古自治区":[110.0,41.5],

"宁夏回族自治区":[105.2,37.0],

"山西省":[111.0,37.0],

"河北省":[114.0,37.8],

"山东省":[116.5,36.0],

"河南省":[111.8,33.5],

"陕西省":[107.5,33.5],

"湖北省":[111.0,30.5],

"江苏省":[119.2,32.5],

"安徽省":[115.5,31.8],

"上海市":[121.0,31.0],

"湖南省":[110.3,27.0],

"江西省":[114.0,27.0],

"浙江省":[118.8,28.5],

"福建省":[116.2,25.5],

"广东省":[113.2,23.1],

"台湾省":[120.5,23.5],

"海南省":[108.0,19.0],

"广西壮族自治区":[107.3,23.0],

"重庆市":[106.5,29.5],

"云南省":[101.0,24.0],

"贵州省":[106.0,26.5],

"四川省":[102.0,30.5],

"甘肃省":[103.0,35.0],

"青海省":[95.0,35.0],

"新疆维吾尔自治区":[85.5,42.5],

"西藏自治区":[85.0,31.5],

"香港特别行政区":[115.1,21.2],

"澳门特别行政区":[112.5,21.2]

}

fig = matplotlib.figure.Figure()

fig.set_size_inches(10, 8) # 设置绘图板尺寸

axes = fig.add_axes((0.1, 0.12, 0.8, 0.8)) # rect = l,b,w,h

# 兰博托投影模式,局部

m = Basemap(projection='lcc', llcrnrlon=77, llcrnrlat=14, urcrnrlon=140, urcrnrlat=51, lat_1=33, lat_2=45, lon_0=100, ax=axes)

# 兰博托投影模式,全图

#m = Basemap(projection='lcc', llcrnrlon=80, llcrnrlat=0, urcrnrlon=140, urcrnrlat=51, lat_1=33, lat_2=45, lon_0=100, ax=axes)

# 圆柱投影模式,局部

#m = Basemap(llcrnrlon=lon_min, urcrnrlon=lon_max, llcrnrlat=lat_min, urcrnrlat=lat_max, resolution='l', ax=axes)

# 正射投影模式

#m = Basemap(projection='ortho', lat_0=36, lon_0=102, resolution='l', ax=axes)

m.readshapefile('res/china-shapefiles-master/china', 'province', drawbounds=True)

m.readshapefile('res/china-shapefiles-master/china_nine_dotted_line', 'section', drawbounds=True)

m.drawcoastlines(color='black') # 洲际线

m.drawcountries(color='black') # 国界线

m.drawparallels(np.arange(lat_min,lat_max,10), labels=[1,0,0,0]) #画经度线

m.drawmeridians(np.arange(lon_min,lon_max,10), labels=[0,0,0,1]) #画纬度线

pset = set()

for info, shape in zip(m.province_info, m.province):

pname = info['OWNER'].strip('\x00')

fcname = info['FCNAME'].strip('\x00')

if pname != fcname: # 不绘制海岛

continue

for key in data.keys():

if key in pname:

if data[key] == 0:

color = '#f0f0f0'

elif data[key] < 10:

color = '#ffaa85'

elif data[key] <100:

color = '#ff7b69'

elif data[key] < 1000:

color = '#bf2121'

else:

color = '#7f1818'

break

poly = Polygon(shape, facecolor=color, edgecolor=color)

axes.add_patch(poly)

pos = provincePos[pname]

text = pname.replace("自治区", "").replace("特别行政区", "").replace("壮族", "").replace("维吾尔", "").replace("回族", "").replace("省", "").replace("市", "")

if text not in pset:

x, y = m(pos[0], pos[1])

axes.text(x, y, text, fontproperties=font_11, color='#00FFFF')

pset.add(text)

axes.legend(handles, labels, bbox_to_anchor=(0.5, -0.11), loc='lower center', ncol=4, prop=font_14)

axes.set_title("2019-nCoV疫情地图", fontproperties=font_14)

FigureCanvasAgg(fig)

fig.savefig('2019-nCoV疫情地图.png')

if __name__ == '__main__':

plot_daily()

plot_distribution()

2019-nCoV疫情曲线

2019-nCoV疫情地图(兰勃托投影)

2019-nCoV疫情地图(圆柱投影)

2019-nCoV疫情地图(正射投影)

4

一、在线直播

将安排千锋最强讲师授课、均是业内顶尖大神。

二、在线辅导

由线下班授课老师担任辅导老师,周一到周六9:30—24:00全程在线,保证每位同学都能得到全面辅导、随时答疑。这些老师都是线下班的讲师,拥有丰富授课经验的讲师。

三、在线辅学系统

通过智能化系统关注每位学生学习进度,对于懈怠、跟不上的同学及时督促与补习。

四、在线学习督促

每班都配有班主任进行班级管理、就业老师,加上招生老师,多重督促,延续千锋“比着学”的良好学习氛围。

五、视频回看

每节课都有高清录播,漏掉的、没听懂的,随时回看,反复学习。

5

在这突如其来的灾难下,很多人很多事都被改变了,在被动之中我们其实可以主动。与其在家闲着,不如立即开始学习,与其苦盼疫情早日结束,不如保持努力坚持进步,因为疫情早晚会过去,一切终会要恢复正轨,但当机遇爆发式来临时,能不能把握住,只看我们是否已经准备好了,是否足够强大。所以,现在开始,千锋帮助你们把危机变机遇。

停课不停学,教学品质不打折,高薪不打折。模式虽有变化,但千锋教育的服务没有变化!千锋学子加油,现在逆境学习,未来就业季傲视群雄!

千锋500万元逆战班助学计划,每人将获得2020元的助学补贴,只有2500个名额,现在同学都已开始在抢名额,错过不要再来怪小千没有提醒到你~另外小千偷偷告诉你一个秘密活动,元宵节和情人节还有双重福利。

特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。

Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.

相关推荐
热点推荐
有人算了一笔账,如果100万的房子,以前公积金首付20%,需要20万

有人算了一笔账,如果100万的房子,以前公积金首付20%,需要20万

知秋侃史
2024-05-18 03:10:11
给《我是歌手》十位“候选歌手”实力排个名,孙楠第5,韩红第2

给《我是歌手》十位“候选歌手”实力排个名,孙楠第5,韩红第2

皮皮电影
2024-05-21 09:22:10
他们这样悼念伊朗总统

他们这样悼念伊朗总统

环球时报新闻
2024-05-20 20:04:42
证监会同意长联科技IPO注册

证监会同意长联科技IPO注册

每日经济新闻
2024-05-21 17:09:17
江苏灌云一村委会承包村民土地到期后不返还,与村民签的10年租期被涂改为20年

江苏灌云一村委会承包村民土地到期后不返还,与村民签的10年租期被涂改为20年

极目新闻
2024-05-20 16:12:43
欧文回应爱德华兹挑衅, 年轻人不要太狂妄, 去问问詹姆斯我有多强

欧文回应爱德华兹挑衅, 年轻人不要太狂妄, 去问问詹姆斯我有多强

赵金玲健康知识
2024-05-21 13:58:57
Lisa和lvmh三公子去逛旗下品牌罗意威,最后Lisa自己掏钱买包

Lisa和lvmh三公子去逛旗下品牌罗意威,最后Lisa自己掏钱买包

李老师坐谈教育
2024-05-21 17:53:24
你见过监狱里有哪些人才?网友:出狱的时候,老板亲自来请

你见过监狱里有哪些人才?网友:出狱的时候,老板亲自来请

金哥说新能源车
2024-05-21 12:09:06
硬汉内贾德:因骂美国出名,还给百姓发钱,因何下台后锒铛入狱?

硬汉内贾德:因骂美国出名,还给百姓发钱,因何下台后锒铛入狱?

WarOH协虎
2024-03-16 21:40:03
中国新首富诞生!460亿美元成功超越马云,给武汉捐了15亿

中国新首富诞生!460亿美元成功超越马云,给武汉捐了15亿

小马哥谈体育
2024-05-21 07:50:02
1换3,郭艾伦交易或敲定,莫兰德被重罚,周鹏去向敲定

1换3,郭艾伦交易或敲定,莫兰德被重罚,周鹏去向敲定

保持热爱0263
2024-05-21 13:13:54
伟大3-0!14万人口小城创奇迹:建队74年后首进欧冠,庆祝如夺冠

伟大3-0!14万人口小城创奇迹:建队74年后首进欧冠,庆祝如夺冠

侃球熊弟
2024-05-21 07:11:49
大明山景区回应强制游客购买大巴车票:必须要买,这是景区规定

大明山景区回应强制游客购买大巴车票:必须要买,这是景区规定

映射生活的身影
2024-05-21 12:55:40
选择题,4年1.7亿和5年2.7亿,季后赛得分王该怎么选?

选择题,4年1.7亿和5年2.7亿,季后赛得分王该怎么选?

大西体育
2024-05-21 10:25:50
乒乓球太原赛:国乒首位出局选手诞生,直拍名将爆冷一轮游输队友

乒乓球太原赛:国乒首位出局选手诞生,直拍名将爆冷一轮游输队友

全言作品
2024-05-21 12:25:54
众人要求处死江青,陈云:若一定要杀,请写“陈云不同意”

众人要求处死江青,陈云:若一定要杀,请写“陈云不同意”

华人星光
2024-05-21 13:01:43
湖南黑老大尹健覆灭记,当年他在天上人间有多狂?此事可见一斑

湖南黑老大尹健覆灭记,当年他在天上人间有多狂?此事可见一斑

一场奇遇日记
2024-04-29 20:58:47
王思聪日本行3美女作伴!双眼无神发福邋遢,网友:身体被掏空?

王思聪日本行3美女作伴!双眼无神发福邋遢,网友:身体被掏空?

花花lo先森
2024-05-09 10:17:15
每体:维拉有意巴萨中卫阿劳霍,计划卖掉卡洛斯腾出位置

每体:维拉有意巴萨中卫阿劳霍,计划卖掉卡洛斯腾出位置

懂球帝
2024-05-21 06:47:15
金融不香了!所有人都知道某行在疯狂降薪,本尊到现在拒不承认

金融不香了!所有人都知道某行在疯狂降薪,本尊到现在拒不承认

热闹吃瓜大姐
2024-05-20 22:14:14
2024-05-21 20:52:49
扣丁学堂
扣丁学堂
扣丁学堂是IT教育领导者
2026文章数 697关注度
往期回顾 全部

健康要闻

在中国,到底哪些人在吃“伟哥”?

头条要闻

已婚男在"王婆说媒"舞台相亲被妻子发现 今天二人离婚

头条要闻

已婚男在"王婆说媒"舞台相亲被妻子发现 今天二人离婚

体育要闻

兄弟们,为了我,拿下冠军吧!

娱乐要闻

杨洋乔欣聊天记录曝光!还牵扯张天爱

财经要闻

重营销轻研发 “扫地茅”股价已跌去78%

科技要闻

微软发AI PC:这次真的能与MacBook竞争了

汽车要闻

四排八座纯电MPV/续航超过800km 翼真L380开启预订

态度原创

房产
手机
数码
游戏
军事航空

房产要闻

教育+医疗+商业连甩王炸,三亚配套大爆发!

手机要闻

八千元买iPhone 15 Pro Max还是vivo灭霸?结果意料之中

数码要闻

光威神武DDR5 7000内存32GB套装699元:海力士A-die颗粒

数毛社编辑盛赞《地狱之刃2》:无与伦比的视觉体验

军事要闻

美方无理指责中方向俄提供军事装备 中国代表当场回击

无障碍浏览 进入关怀版