天天看點

大資料可視化案例二:資料可視化地圖

Echart:

ECharts,一個純 Javascript 的圖表庫,可以流暢的運作在 PC 和移動裝置上,相容目前絕大部分浏覽器(IE8/9/10/11,Chrome,Firefox,Safari等),底層依賴輕量級的 Canvas 類庫 ZRender,提供直覺,生動,可互動,可高度個性化定制的資料可視化圖表。

ECharts 提供了正常的折線圖,柱狀圖,散點圖,餅圖,K線圖,用于統計的盒形圖,用于地理資料可視化的地圖,熱力圖,線圖,用于關系資料可視化的關系圖,treemap,多元資料可視化的平行坐标,還有用于 BI 的漏鬥圖,儀表盤,并且支援圖與圖之間的混搭。

在本次内容中,使用Pyechats來實作新冠肺炎疫情地圖的繪制。

第一步:擷取實時的新冠肺炎資料

import requests
from lxml import etree
import re
import json

class Get_data():
    #擷取資料
    def get_data(self):
        response = requests.get("https://voice.baidu.com/act/newpneumonia/newpneumonia/")
        with open(\'html.txt\', \'w\') as file:
            file.write(response.text)
    #提取更新時間
    def get_time(self):
        with open(\'html.txt\',\'r\') as file:
            text = file.read()
        #正規表達式,傳回的是清單,提取最新更新時間
        time = re.findall(\'"mapLastUpdatedTime":"(.*?)"\', text)[0]
        return time
    #解析資料
    def parse_data(self):
        with open(\'html.txt\', \'r\') as file:
            text = file.read()
        html = etree.HTML(text)
        result = html.xpath(\'//script[@type="application/json"]/text()\')
        result = result[0]
        result = json.loads(result)
        #轉換成字元串
        result = json.dumps(result[\'component\'][0][\'caseList\'])
        with open(\'data.json\', \'w\') as file:
            file.write(result)
            print(\'資料已寫入json檔案。。。\')
      

  

第二步:繪制地圖

pyecharts的地圖官方源碼:

from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.faker import Faker

c = (
    Map()
    .add("商家A", [list(z) for z in zip(Faker.provinces, Faker.values())], "china")
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Map-VisualMap(連續型)"),
        visualmap_opts=opts.VisualMapOpts(max_=200),
    )
)
      

  

效果:

大資料可視化案例二:資料可視化地圖

 第二步:資料可視化地圖

from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.faker import Faker
import os

class Draw_map():
    #判斷是否存在存放地圖的檔案夾,沒有的話建立檔案夾
    def __init__(self):
        if not os.path.exists(\'./map/china\'):
            os.makedirs(\'./map/china\')
    #将RGB轉換為繪制地圖需要的十六進制的表達形式
    def get_colour(self,a,b,c):
        result = \'#\' + \'\'.join(map((lambda x: "%02x" % x), (a,b,c)))
        return result.upper()
    #繪制每個城市的地圖
    def to_map_city(self,area, variate,province,update_time):
        #顯示辨別欄的顔色分層表示
        pieces = [
            {"max": 99999999, "min": 10000, "label": "≥10000", "color": self.get_colour(102, 2, 8)},
            {"max": 9999, "min": 1000, "label": "1000-9999", "color": self.get_colour(140, 13, 13)},
            {"max": 999, "min": 500, "label": "500-999", "color": self.get_colour(204, 41, 41)},
            {"max": 499, "min": 100, "label": "100-499", "color": self.get_colour(255, 123, 105)},
            {"max": 99, "min": 50, "label": "50-99", "color": self.get_colour(255, 170, 133)},
            {"max": 49, "min": 10, "label": "10-49", "color": self.get_colour(255,202,179)},
            {"max": 9, "min": 1, "label": "1-9", "color": self.get_colour(255,228,217)},
            {"max": 0, "min": 0, "label": "0", "color": self.get_colour(255,255,255)},
              ]
        #繪制地圖
        c = (
            # 設定地圖大小
            Map(init_opts=opts.InitOpts(width = \'1000px\', height=\'880px\'))
            .add("累計确診人數", [list(z) for z in zip(area, variate)], province, is_map_symbol_show=False)
            # 設定全局變量  is_piecewise設定資料是否連續,split_number設定為分段數,pices可自定義資料分段
            # is_show設定是否顯示圖例
            .set_global_opts(
                title_opts=opts.TitleOpts(title="%s地區疫情地圖分布"%(province), subtitle = \'截止%s  %s省疫情分布情況\'%(update_time,province), pos_left = "center", pos_top = "10px"),
                legend_opts=opts.LegendOpts(is_show = False),
                visualmap_opts=opts.VisualMapOpts(max_=200,is_piecewise=True,
                                                  pieces=pieces,
                                                  ),
            )
            .render("./map/china/{}疫情地圖.html".format(province))
        )

    # 繪制全國的地圖
    def to_map_china(self, area,variate,update_time):
        pieces = [{"max": 999999, "min": 1001, "label": ">10000", "color": "#8A0808"},
                  {"max": 9999, "min": 1000, "label": "1000-9999", "color": "#B40404"},
                  {"max": 999, "min": 100, "label": "100-999", "color": "#DF0101"},
                  {"max": 99, "min": 10, "label": "10-99", "color": "#F78181"},
                  {"max": 9, "min": 1, "label": "1-9", "color": "#F5A9A9"},
                  {"max": 0, "min": 0, "label": "0", "color": "#FFFFFF"},
                  ]

        c = (
            # 設定地圖大小
            Map(init_opts=opts.InitOpts(width=\'1000px\', height=\'880px\'))
                .add("累計确診人數", [list(z) for z in zip(area, variate)], "china", is_map_symbol_show=False)
                .set_global_opts(
                title_opts=opts.TitleOpts(title="中國疫情地圖分布", subtitle=\'截止%s 中國疫情分布情況\'%(update_time), pos_left="center", pos_top="10px"),
                legend_opts=opts.LegendOpts(is_show=False),
                visualmap_opts=opts.VisualMapOpts(max_=200, is_piecewise=True,
                                                  pieces=pieces,
                                                  ),
            )
            .render("./map/中國疫情地圖.html")
        )
      

  

第三步:

使用資料來繪制地圖:

import json
import map_draw
import data_get

with open(\'data.json\',\'r\') as file:
    data = file.read()
    data = json.loads(data)
    map = map_draw.Draw_map()
    datas = data_get.Get_data()
    datas.get_data()
    update_time = datas.get_time()
    datas.parse_data()
#中國疫情地圖資料
def china_map():
    area = []
    confirmed = []
    for each in data:
        area.append(each[\'area\'])
        confirmed.append(each[\'confirmed\'])
    map.to_map_china(area,confirmed,update_time)

#省份疫情地圖資料
def province_map():
    for each in data:
        city = []
        confirmeds = []
        province = each[\'area\']
        for each_city in each[\'subList\']:
            city.append(each_city[\'city\']+"市")
            confirmeds.append(each_city[\'confirmed\'])
            map.to_map_city(city,confirmeds,province,update_time)
        if province == \'上海\' or \'北京\' or \'天津\' or \'重慶\' or \'香港\':
            for each_city in each[\'subList\']:
                city.append(each_city[\'city\'])
                confirmeds.append(each_city[\'confirmed\'])
                map.to_map_city(city,confirmeds,province,update_time)
      

  

 

效果:

全國:

大資料可視化案例二:資料可視化地圖

 内蒙古自治區:

大資料可視化案例二:資料可視化地圖

 本次内容參考自:

https://pyecharts.org/#/zh-cn/intro

http://gallery.pyecharts.org/#/Map/README

https://www.jianshu.com/p/3e71d73694fa

https://www.jianshu.com/p/d2474e9bce6e

https://www.bilibili.com/medialist/play/ml317727151

大資料可視化案例二:資料可視化地圖