echart制作省市疫情地图
程序员文章站
2024-03-19 23:18:58
...
看到丁香医生疫情数据地图,觉得比较好看,便参考网上模板,模仿着做了一个。
参考:https://www.52pojie.cn/thread-1096756-1-1.html
第一步:获取疫情数据信息(数据源:丁香医生)
import datetime
from fake_useragent import UserAgent
import requests
import re
ua = UserAgent()
headers = {'User-Agent': ua.random}
url = "https://c.m.163.com/ug/api/wuhan/app/index/feiyan-data-list?t=1580469818264"
#爬取疫情数据
def geturl(url):
try:
response = requests.get(url,headers=headers)
print(response.status_code)
if response.status_code == 200:
pat_province = 'list":([\s\S]*\])'
files = str(response.text)
dataall = re.compile(pat_province).findall(files)
data2 = dataall[0].replace('null','None')
list_datas_1 = eval(data2)
print(list_datas_1)
return list_datas_1
else:
print('返回代码:'+response.status_code)
return None
except Exception as e:
print('此页有问题!',e)
return None
certain = geturl(url)
with open('certain.txt','w',encoding='utf-8') as f:
for item in certain:
f.write(json.dumps(item,ensure_ascii=False))
f.write('/n')
print('保存完毕')
第二步:数据处理,获取各市对应的数据,在制作过程中发现区县名字为简称,无法与echart中的地图中的名称完全对应,便从国家统计局官网爬取了了标准名称,将简称替换为标准名称。
province = '四川' #不同省份可直接替换
#生成本省疫情列表
def makedict(list):
dict1 = {}
df = pd.read_csv('chinastats.txt') # 爬取的各省标准名称文件
zhixiashi = ['北京','上海','重庆','天津'] #直辖市跟其他省稍有区别,单独提出来进行分类
for item in list:
if(item['province'] == province):
if province in zhixiashi:
countrys = df['区'][df['省'].str.contains(province)].unique()
else:
countrys = df['市'][df['省'].str.contains(province)].unique()
for country in countrys:
if fuzz.ratio(item['name'],country) > 0.3: #简称与全称进行模糊匹配,将全称命名为字典关键词,并赋值
dict1[country] = int(item["confirm"])
print(dict1)
return dict1
dict_data=makedict(certain)
第三部,根据现有数据,利用echart 地图进行展示。pyecahrt 获取错误时,请参照ecahrt官方文档对echart包进行更新
def makemap(dict):
# 省和直辖市
province_distribution = dict
# print(dict)
value=province_distribution.values()
# maptype='china' 只显示全国直辖市和省级
yesterday = datetime.date.today() - datetime.timedelta(days=1)
title = str(int(yesterday.strftime("%Y%m%d")))+"{}疫情地图".format(province)
map = Map()
map.set_global_opts(
title_opts=opts.TitleOpts(title=title),
visualmap_opts=opts.VisualMapOpts(max_=200, is_piecewise=True,
pieces=[
{"max": 1000, "min": 61, "label": ">61", "color": "#780707"}, #数据范围分段,分颜色,可以根据数据大小具体分配大小
{"max": 60, "min": 51, "label": "51-60", "color": "#8A0808"},
{"max": 50, "min": 41, "label": "41-50", "color": "#B40404"},
{"max": 40, "min": 31, "label": "31-40", "color": "#CD1111"},
{"max": 30, "min": 21, "label": "21-30", "color": "#DF0101"},
{"max": 20, "min": 11, "label": "11-20", "color": "#F68181"},
{"max": 10, "min": 1, "label": "1-10", "color": "#F5A9A9"},
{"max": 0, "min": 0, "label": "0", "color": "#FFFFFF"},
], ) #最大数据范围,分段
)
map.add(title, data_pair=province_distribution.items(), maptype=province, is_roam=True)
map.render(province+'疫情地图.html')
上一篇: Oracle排序后获取第一条和最后一条值
下一篇: Echart.js 入门案例