pycharts实现地图可视化(世界地图、中国地图、省份地图)

使用之前先导入包,pycharts的1.x版本和0.5不兼容,我的环境之前是1.x版本,所以下面都是以1.x版本为例。

from pyecharts.charts import Map
from pyecharts.charts import *
from pyecharts.globals import ThemeType
from pyecharts import options as opts
#创建一个map对象
#init_opts用来初始化配置
#初始化配置项包括
'''
# 图表画布宽度,css 长度单位。
    width: str = "900px",
    # 图表画布高度,css 长度单位。
    height: str = "500px",
    # 图表 ID,图表唯一标识,用于在多图表时区分。
    chart_id: Optional[str] = None,
    # 渲染风格,可选 "canvas", "svg"
    # # 参考 `全局变量` 章节
    renderer: str = RenderType.CANVAS,
    # 图表标题
    page_title: str = "Awesome-pyecharts",
    # 图表样式
    theme: str = "white",
    # 图表背景颜色
    bg_color: Optional[str] = None,
    # 远程 js host,如不设置默认为 https://assets.pyecharts.org/assets/"
    # 参考 `全局变量` 章节
    js_host: str = "",
'''
china_map = Map(init_opts=opts.InitOpts(theme=ThemeType.MACARONS ,width="1000px",height='700px',page_title="2019_nCoV-中国疫情地图"))
#全局配置项
    china_map.set_global_opts(title_opts=opts.TitleOpts(title="2019_nCoV-中国疫情地图"))
    #series_name
    #maptype是地图的类型china就是中国地图,world就是世界地图
    #湖北就是湖北地图,山东就是山东地图,is_selected=True,#控制开始时位于图标上方的小按钮是否选中
    china_map.add(series_name="确诊病例", data_pair=province_total, maptype='china', is_selected=True,#控制开始时的小按钮是否选中
                  center=["100%","100%"],)
    china_map.set_global_opts(title_opts=opts.TitleOpts(title="2019_nCoV-中国疫情地图"),
                              visualmap_opts=opts.VisualMapOpts(is_piecewise=True,
                                                                pieces=[
                                                                    {"min": 201, "label": '>300'},
                                                                    {"min": 101, "max": 200,"label":'101-200'},
                                                                    # 不指定 max,表示 max 为无限大
                                                                    {"min": 10, "max": 100, "label": '10-100'},

                                                                    {"min": 0, "max": 9, "label": '0-9'}]))
#is_show=True用于控制地图上是否显示省份,国家,地市的名字
    china_map.set_series_opts(label_opts=opts.LabelOpts(is_show=True))
    page = Page()
    #创建一个页面对象,使用add方法把地图加入到该页面,用于使用一个页面显示多张图表的问题。
    page.add(china_map)
    #生成一个html文件
    page.render(path="2019_nCoV-疫情地图.html")
    
    

pyechart给使用用户提供了一套主题样式,使用户对其的使用更加方便。pyecharts.globals中ThemeType所有主题风格,修改上面代码中的theme参数即可。
CHALK = ‘chalk’ #粉笔风
DARK = ‘dark’ #暗黑风
ESSOS = ‘essos’ #厄索斯大陆
INFOGRAPHIC = ‘infographic’ #信息图
LIGHT = ‘light’ #明亮风格
MACARONS = ‘macarons’ #马卡龙
PURPLE_PASSION = ‘purple-passion’ #紫色激情
ROMA = ‘roma’ #石榴
ROMANTIC = ‘romantic’ #浪漫风
SHINE = ‘shine’ #闪耀风
VINTAGE = ‘vintage’ #复古风
WALDEN = ‘walden’ #瓦尔登湖
WESTEROS = ‘westeros’ #维斯特洛大陆
WHITE = ‘white’ #洁白风
WONDERLAND = ‘wonderland’ #仙境
pycharts实现地图可视化(世界地图、中国地图、省份地图)_第1张图片
pycharts实现地图可视化(世界地图、中国地图、省份地图)_第2张图片
参考博客:
用PyEcharts实现数据可视化快速上手指南
官方文档1.X版本
InitOpts:初始化配置项
Pyechart 所有主题样式
PyEcharts——地图-数据可视化-画图
完整代码:

import requests
import json
from pyecharts.charts import Map
from pyecharts.charts import *
from pyecharts.globals import ThemeType
from pyecharts import options as opts
from 新冠病毒.EnglishCountryName import encountry
def getData():
    url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'
    response = requests.get(url=url).json()
    data = json.loads(response['data'])
    print(data)
    return data
def parser():
    data = getData()
    lastUpdateTime = data["lastUpdateTime"]
    chinaTotal = data["chinaTotal"]
    print("更新时间:" + lastUpdateTime)
    chinaTotal = {"确诊":chinaTotal['confirm'],"治愈":chinaTotal['heal'],"死亡":chinaTotal['dead'],"疑似":chinaTotal['suspect'],"境外输入":chinaTotal['importedCase']}
    print(chinaTotal)
    # 中国境内
    area_china = data['areaTree']#area_china是列表
    china_province = area_china[0]['children']#china_province也是列表
    area_china_province_dict = {}
    area_china_city_dict = {}
    # 34个省直辖区
    for i in range(0,len(china_province)):
        # 各省份名称  china_province[i]字典类型
        li = []
        province_name = china_province[i]["name"]
        # 各省今天新增确认
        province_today_confirm = china_province[i]["today"]['confirm']
        # 各省总共
        province_total_confirm =  china_province[i]['total']['confirm']
        province_total_suspect = china_province[i]['total']['suspect']
        province_total_dead = china_province[i]['total']['dead']
        province_total_heal = china_province[i]['total']['heal']
        province_total_healRate = china_province[i]['total']['healRate']
        province_total_deadRate = china_province[i]['total']['deadRate']
        li.append(province_today_confirm)
        li.append(province_total_confirm)
        li.append(province_total_suspect)
        li.append(province_total_dead)
        li.append(province_total_heal)
        li.append(province_total_healRate)
        li.append(province_total_deadRate)
        area_china_province_dict[province_name] = li
        #获取省份地市
        for j in range(0, len(china_province[i]['children'])):
            city_li = []
            city_name = china_province[i]['children'][j]["name"]
            city_today_confirm = china_province[i]['children'][j]["today"]['confirm']
            city_li.append(city_today_confirm)
            # for value in china_province[i]['children'][j]["total"].values():
            #     city_li.append(value)
            city_total_confirm = china_province[i]['children'][j]["total"]['confirm']
            city_total_suspect = china_province[i]['children'][j]["total"]['suspect']
            city_total_dead = china_province[i]['children'][j]["total"]['dead']
            city_total_heal = china_province[i]['children'][j]["total"]['heal']
            city_total_healRate = china_province[i]['children'][j]["total"]['healRate']
            city_total_deadRate = china_province[i]['children'][j]["total"]['deadRate']
            city_li.append(city_total_confirm)
            city_li.append(city_total_suspect)
            city_li.append(city_total_dead)
            city_li.append(city_total_heal)
            city_li.append(city_total_healRate)
            city_li.append(city_total_deadRate)
            area_china_city_dict[city_name] = city_li
    return area_china_province_dict,area_china_city_dict

def drawMap(china_province,china_city):
    page = Page()
    province_total = []
    for key,value in china_province.items():
        province_detail = []
        province_detail.append(key)
        province_detail.append(value[1])
        province_total.append(province_detail)
    # print(province_total)
    china_map = Map(init_opts=opts.InitOpts(theme=ThemeType.MACARONS ,width="1000px",height='700px',page_title="2019_nCoV-中国疫情地图"))
    china_map.set_global_opts(title_opts=opts.TitleOpts(title="2019_nCoV-中国疫情地图"))
    china_map.add(series_name="确诊病例", data_pair=province_total, maptype='china', is_selected=True,#控制开始时的小按钮是否选中
                  center=["100%","100%"],)
    china_map.set_global_opts(title_opts=opts.TitleOpts(title="2019_nCoV-中国疫情地图"),
                              visualmap_opts=opts.VisualMapOpts(is_piecewise=True,
                                                                pieces=[
                                                                    {"min": 201, "label": '>300'},
                                                                    {"min": 101, "max": 200,"label":'101-200'},
                                                                    # 不指定 max,表示 max 为无限大
                                                                    {"min": 10, "max": 100, "label": '10-100'},

                                                                    {"min": 0, "max": 9, "label": '0-9'}]))
    china_map.set_series_opts(label_opts=opts.LabelOpts(is_show=True))
    page.add(china_map)

    province_city_total = []
    for key, value in china_city.items():
        province_city_detail = []
        province_city_detail.append(key)
        province_city_detail.append(value[1])
        province_city_total.append(province_city_detail)
    # print(province_city_total)
    hubei = []
    for i in range(0, 17):
        if province_city_total[i][0] == '神农架':
            province_city_total[i][0] = '神农架林区'
        elif province_city_total[i][0] == '恩施州':
            province_city_total[i][0] = '恩施土家族苗族自治州'
        else:
            province_city_total[i][0] = str(province_city_total[i][0]) + '市'
        hubei.append(province_city_total[i])
    # print(hubei)
    hubei_map = Map(init_opts=opts.InitOpts(theme=ThemeType.WALDEN, width="1000px", height='700px',
                                            page_title="2019_nCoV-湖北省疫情地图"))
    # print(provice,values)
    hubei_map.set_global_opts(title_opts=opts.TitleOpts(title="2019_nCoV-湖北省疫情地图"))
    hubei_map.add(series_name="确诊病例", data_pair=hubei, maptype='湖北', is_selected=True,
                  is_map_symbol_show=False)
    hubei_map.set_global_opts(title_opts=opts.TitleOpts(title="2019_nCoV-湖北省疫情地图"),
                              visualmap_opts=opts.VisualMapOpts(is_piecewise=True,
                                                                pieces=[
                                                                    {"min": 1501, "label": '>1501'},
                                                                    # 不指定 max,表示 max 为无限大
                                                                    {"min": 100, "max": 400, "label": '100-400'},
                                                                    {"min": 401, "max": 1000, "label": '401-1000'},
                                                                    {"min": 1001, "max": 1500, "label": '1001-1500'},
                                                                    ]))
    hubei_map.set_series_opts(label_opts=opts.LabelOpts(is_show=True))  # 控制是否显示国家名
    page.add(hubei_map)


    world_data = getData()
    print(world_data)
    print(world_data['lastUpdateTime'])
    # print(world_data['chinaTotal'])
    global_country_confirm = []
    for i in range(0,len(world_data['areaTree'])):
        # print(world_data['areaTree'][i])#获取每个国家所有的疫情信息
        li = []
        dead = []
        # li.append(world_data['areaTree'][i])
        country_name = world_data['areaTree'][i]["name"]
        # li.append(world_data['areaTree'][i]["today"]['confirm'])
        li.append(world_data['areaTree'][i]["total"]['confirm'])
        # li.append(world_data['areaTree'][i]["total"]['head'])
        global_country_confirm.append([country_name,li])
    print(global_country_confirm)#['中国', [70, 81186, 81186]]
    en = encountry()
    for i in range(len(global_country_confirm)):
        for key, value in en.items():
            if global_country_confirm[i][0] == key :
                global_country_confirm[i][0] = value
        print(global_country_confirm[i])

    world_map = Map(init_opts=opts.InitOpts(theme=ThemeType.WALDEN))
    world_map.add(series_name="确诊病例", data_pair=global_country_confirm, maptype='world', is_selected=True, is_map_symbol_show=False)
    world_map.set_global_opts(title_opts=opts.TitleOpts(title="2019_nCoV-世界疫情地图"),
                              visualmap_opts=opts.VisualMapOpts(is_piecewise=True,
                                                                pieces=[
                                                                    {"min": 101, "label": '>100'},
                                                                    # 不指定 max,表示 max 为无限大
                                                                    {"min": 10, "max": 100, "label": '10-100'},
                                                                    {"min": 0, "max": 9, "label": '0-9'}]))
    world_map.set_series_opts(label_opts=opts.LabelOpts(is_show=False))#控制是否显示国家名
    page.add(world_map)

    # 重点国家的死亡率







    page.render(path="2019_nCoV-疫情地图.html")




if __name__ == '__main__':
    china_province,china_city = parser()
    drawMap(china_province, china_city)


你可能感兴趣的:(python,爬虫)