Python抓新型冠状病毒肺炎疫情数据并绘制全国疫情分布的代码实例
作者:蒜泥的冬天 发布时间:2022-10-11 23:14:40
标签:Python,新型冠状病毒
运行结果(2020-2-4日数据)
数据来源
news.qq.com/zt2020/page/feiyan.htm
抓包分析
日报数据格式
"chinaDayList": [{
"date": "01.13",
"confirm": "41",
"suspect": "0",
"dead": "1",
"heal": "0"
}, {
"date": "01.14",
"confirm": "41",
"suspect": "0",
"dead": "1",
"heal": "0"
}, {
"date": "01.15",
"confirm": "41",
"suspect": "0",
"dead": "2",
"heal": "5"
}, {
。。。。。。
全国各地疫情数据格式
"lastUpdateTime": "2020-02-04 12:43:19",
"areaTree": [{
"name": "中国",
"children": [{
"name": "湖北",
"children": [{
"name": "武汉",
"total": {
"confirm": 6384,
"suspect": 0,
"dead": 313,
"heal": 303
},
"today": {
"confirm": 1242,
"suspect": 0,
"dead": 48,
"heal": 79
}
}, {
"name": "黄冈",
"total": {
"confirm": 1422,
"suspect": 0,
"dead": 19,
"heal": 36
},
"today": {
"confirm": 176,
"suspect": 0,
"dead": 2,
"heal": 9
}
}, {
。。。。。。
地图数据
github.com/dongli/china-shapefiles
代码实现
#%%
import time, json, requests
from datetime import datetime
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.font_manager import FontProperties
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
import numpy as np
import jsonpath
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
#%%
# 全国疫情地区分布(省级确诊病例)
def catch_cn_disease_dis():
timestamp = '%d'%int(time.time()*1000)
url_area = ('https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'
'&callback=&_=') + timestamp
world_data = json.loads(requests.get(url=url_area).json()['data'])
china_data = jsonpath.jsonpath(world_data,
expr='$.areaTree[0].children[*]')
list_province = jsonpath.jsonpath(china_data, expr='$[*].name')
list_province_confirm = jsonpath.jsonpath(china_data, expr='$[*].total.confirm')
dic_province_confirm = dict(zip(list_province, list_province_confirm))
return dic_province_confirm
area_data = catch_cn_disease_dis()
print(area_data)
#%%
# 抓取全国疫情按日期分布
'''
数据源:
"chinaDayList": [{
"date": "01.13",
"confirm": "41",
"suspect": "0",
"dead": "1",
"heal": "0"
}, {
"date": "01.14",
"confirm": "41",
"suspect": "0",
"dead": "1",
"heal": "0"
}
'''
def catch_cn_daily_dis():
timestamp = '%d'%int(time.time()*1000)
url_area = ('https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'
'&callback=&_=') + timestamp
world_data = json.loads(requests.get(url=url_area).json()['data'])
china_daily_data = jsonpath.jsonpath(world_data,
expr='$.chinaDayList[*]')
# 其实没必要单独用list存储,json可读性已经很好了;这里这样写仅是为了少该点老版本的代码
list_dates = list() # 日期
list_confirms = list() # 确诊
list_suspects = list() # 疑似
list_deads = list() # 死亡
list_heals = list() # 治愈
for item in china_daily_data:
month, day = item['date'].split('.')
list_dates.append(datetime.strptime('2020-%s-%s'%(month, day), '%Y-%m-%d'))
list_confirms.append(int(item['confirm']))
list_suspects.append(int(item['suspect']))
list_deads.append(int(item['dead']))
list_heals.append(int(item['heal']))
return list_dates, list_confirms, list_suspects, list_deads, list_heals
list_date, list_confirm, list_suspect, list_dead, list_heal = catch_cn_daily_dis()
print(list_date)
#%%
# 绘制每日确诊和死亡数据
def plot_cn_daily():
# list_date, list_confirm, list_suspect, list_dead, list_heal = catch_cn_daily_dis()
plt.figure('novel coronavirus', facecolor='#f4f4f4', figsize=(10, 8))
plt.title('全国新型冠状病毒疫情曲线', fontsize=20)
print('日期元素数:', len(list_date), "\n确诊元素数:", len(list_confirm))
plt.plot(list_date, list_confirm, label='确诊')
plt.plot(list_date, list_suspect, label='疑似')
plt.plot(list_date, list_dead, label='死亡')
plt.plot(list_date, list_heal, label='治愈')
xaxis = plt.gca().xaxis
# x轴刻度为1天
xaxis.set_major_locator(matplotlib.dates.DayLocator(bymonthday=None, interval=1, tz=None))
xaxis.set_major_formatter(mdates.DateFormatter('%m月%d日'))
plt.gcf().autofmt_xdate() # 优化标注(自动倾斜)
plt.grid(linestyle=':') # 显示网格
plt.xlabel('日期',fontsize=16)
plt.ylabel('人数',fontsize=16)
plt.legend(loc='best')
plot_cn_daily()
#%%
# 绘制全国省级行政区域确诊分布图
count_iter = 0
def plot_cn_disease_dis():
# area_data = catch_area_distribution()
font = FontProperties(fname='res/coure.fon', size=14)
# 经纬度范围
lat_min = 10 # 纬度
lat_max = 60
lon_min = 70 # 经度
lon_max = 140
# 标签颜色和文本
legend_handles = [
matplotlib.patches.Patch(color='#7FFFAA', alpha=1, linewidth=0),
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),
]
legend_labels = ['0人', '1-10人', '11-100人', '101-1000人', '>1000人']
fig = plt.figure(facecolor='#f4f4f4', figsize=(10, 8))
# 新建区域
axes = fig.add_axes((0.1, 0.1, 0.8, 0.8)) # left, bottom, width, height, figure的百分比,从figure 10%的位置开始绘制, 宽高是figure的80%
axes.set_title('全国新型冠状病毒疫情地图(确诊)', fontsize=20) # fontproperties=font 设置失败
# bbox_to_anchor(num1, num2), num1用于控制legend的左右移动,值越大越向右边移动,num2用于控制legend的上下移动,值越大,越向上移动。
axes.legend(legend_handles, legend_labels, bbox_to_anchor=(0.5, -0.11), loc='lower center', ncol=5) # prop=font
china_map = Basemap(llcrnrlon=lon_min, urcrnrlon=lon_max, llcrnrlat=lat_min, urcrnrlat=lat_max, resolution='l', ax=axes)
# labels=[True,False,False,False] 分别代表 [left,right,top,bottom]
china_map.drawparallels(np.arange(lat_min,lat_max,10), labels=[1,0,0,0]) # 画经度线
china_map.drawmeridians(np.arange(lon_min,lon_max,10), labels=[0,0,0,1]) # 画纬度线
china_map.drawcoastlines(color='black') # 洲际线
china_map.drawcountries(color='red') # 国界线
china_map.drawmapboundary(fill_color = 'aqua')
# 画中国国内省界和九段线
china_map.readshapefile('res/china-shapefiles-master/china', 'province', drawbounds=True)
china_map.readshapefile('res/china-shapefiles-master/china_nine_dotted_line', 'section', drawbounds=True)
global count_iter
count_iter = 0
# 内外循环不能对调,地图中每个省的数据有多条(绘制每一个shape,可以去查一下第一条“台湾省”的数据)
for info, shape in zip(china_map.province_info, china_map.province):
pname = info['OWNER'].strip('\x00')
fcname = info['FCNAME'].strip('\x00')
if pname != fcname: # 不绘制海岛
continue
is_reported = False # 西藏没有疫情,数据源就不取不到其数据
for prov_name in area_data.keys():
count_iter += 1
if prov_name in pname:
is_reported = True
if area_data[prov_name] == 0:
color = '#f0f0f0'
elif area_data[prov_name] <= 10:
color = '#ffaa85'
elif area_data[prov_name] <= 100:
color = '#ff7b69'
elif area_data[prov_name] <= 1000:
color = '#bf2121'
else:
color = '#7f1818'
break
if not is_reported:
color = '#7FFFAA'
poly = Polygon(shape, facecolor=color, edgecolor=color)
axes.add_patch(poly)
plot_cn_disease_dis()
print('迭代次数', count_iter)
来源:https://blog.csdn.net/shineych/article/details/104173449
0
投稿
猜你喜欢
- 本次我们选择的安卓游戏对象叫“单词英雄”,大家可以先下载这个游戏。游戏的界面是这样的:通过选择单词的意思进行攻击,选对了就正常攻击,选错了就
- 如何用ADO批量更新记录?是的,ADO有这项功能,不过好像用的人不太多(不了解还是不会用呢?):<HTML> &nbs
- asp之家注:如果你学习过asp,并且在网络公司上过班,一定会接触到网购系统,网购系统可以说是一个典型的程序类型,而其中最重要,也是最关键的
- 本文实例讲述了Zend Framework教程之资源(Resources)用法。分享给大家供大家参考,具体如下:Zend_Applicati
- opencv-python打开USB或笔记本前置摄像头代码其中video_index是摄像头编号,一般前置摄像头为0,USB摄像头为1或2.
- 日常我们见的多的水印大都是做到图片里的,我依据html元素的css position定位作出这个 * 印,供大家参考<!DOCTYPE
- 关于mysql数据库在Linux下的应用一直以来都是我认为比较棘手的,这次通过搭建Linux学习环境顺便研究和学习Mysql数据库在Linu
- 以前我就是一篇博文 就给出一个好用的函数,它在我几篇博文中被广泛运用的。最近看了不少东西,于是便有了这篇博文,以梳理我学到的新东西。毫无疑问
- 为了防止某些别有用心的人从外部访问数据库,盗取数据库中的用户姓名、密码、信用卡号等其他重要信息,在我们创建数据库驱动的解决方案时,我们首先需
- 这篇文章主要介绍了jekins配置python脚本定时任务过程图解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价
- 本文记录的要实现的功能类似于 MySQL 中的 ORDER BY,上个项目中有遇到这样的一个需求。 要求:从两个不同的表中获取各自的4条数据
- 本文主要是基于Python Opencv 实现的图像分割,其中使用到的opencv的函数有:使用 OpenCV 函数 cv::filter2
- 在oracle数据库的开发中,常因为时间的问题大费周章,所以特地将ORACLE数据的日期函数收藏致此。乃供他日所查也。 add_months
- 内容摘要: 网页的色彩搭配往往是网友们感到头疼的问题,尤其是那些完全没有美术基础的网友。到底用
- 使用 pdb 进行调试pdb 是 python 自带的一个包,为 python 程序提供了一种交互的源代码调试功能,主要特性包括设置断点、单
- 原文:http://blog.rexsong.com/?p=746#comments加速的关键,不是降低重量,而是减少个数。如果重量在200
- 如下所示:#os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。这个列表以字母顺序。 它不包括 '.&
- 1 丰富的二维动画/图形和视音频表现 Rich 2D animation/graphics with audio and video这点毋庸
- 1、执行环境说明python版本3.7直接使用pip进行安装pywin32、pyinstallerpip install pywin32pi
- 可能很多人遇到过这个错误,当使用setup.py安装python2.7图像处理模块PIL时,python默认会寻找电脑上以安装的vs2008