1. 程式人生 > 實用技巧 >python-pyecharts 疫情資料視覺化

python-pyecharts 疫情資料視覺化

畫圖程式碼檔案

draw_picture.py

from pyecharts import options as opts
from pyecharts.charts import Map, Page
from pyecharts.faker import Faker
from pyecharts.components import Table
from pyecharts.charts import Line, Bar
from pyecharts.globals import ThemeType
from datetime import date
from json_data import province_data_sum, province_data_now
from snapshot_selenium import snapshot
from pyecharts.render import make_snapshot


# 生成全國疫情確診人數累計地圖
def get_map_old_data() -> map:
    print(province_data_sum)
    update_date = date.today()
    map = (
        Map(init_opts=opts.InitOpts(theme=ThemeType.WHITE, width='100%', height='900px'))
            .add("全國累計確診人數", province_data_sum, "china", is_map_symbol_show=False)
            .set_global_opts(
            title_opts=opts.TitleOpts(
                title="新冠狀病毒全國疫情地圖統計",
                subtitle="更新日期:{}".format(update_date),
            ),
            # 視覺對映配置項
            visualmap_opts=opts.VisualMapOpts(
                is_show=True,  # 是否顯示
                min_=0,  # 左下角刻度最小值
                max_=2000,
                range_color=['#FFFFFF', '#F7DC6F', '#F4D03F', '#F1C40F', '#C0392B', '#A93226'],  # 顏色過濾配置
            ),
        )# .render('img/全國疫情視覺化map.html')
    )
    # make_snapshot(snapshot, map.render(), 'img/全國疫情視覺化map.gif')
    return map


# 生成全國疫情當前確診人數地圖
def get_map_now_data() -> map:
    print(province_data_now)
    update_date = date.today()
    map = (
        Map(init_opts=opts.InitOpts(theme=ThemeType.WHITE, width='100%', height='900px'))
            .add("全國現確診人數", province_data_now, "china", is_map_symbol_show=False)
            .set_global_opts(
            title_opts=opts.TitleOpts(
                title="新冠狀病毒全國疫情地圖統計",
                subtitle="更新日期:{}".format(update_date),
            ),
            # 視覺對映配置項
            visualmap_opts=opts.VisualMapOpts(
                is_show=True,  # 是否顯示
                min_=0,  # 左下角刻度最小值
                max_=100,
                range_color=['#FFFFFF', '#F1C40F', '#D4AC0D']  # 顏色過濾配置
            )
        )
    )
    # make_snapshot(snapshot, map.render(), 'img/全國疫情視覺化map1.gif')
    return map


# 生成折線統計圖
def get_line_pic():
    from json_data import province_data_tuple
    c = (
        Line(init_opts=opts.InitOpts(width="100%",
                                     # 設定動畫
                                     animation_opts=opts.AnimationOpts(
                                         animation_delay=1000,
                                         animation_duration=10000,
                                        )
                                     ))
            .add_xaxis(province_data_tuple[0])
            .add_yaxis(
            "累計感染人數",
            province_data_tuple[1],
            # areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
            label_opts=opts.LabelOpts(is_show=False),
        )
            .add_yaxis(
            "累計治癒人數",
            province_data_tuple[2],
            # areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
            label_opts=opts.LabelOpts(is_show=False),
        )
            .add_yaxis(
            "累計死亡人數",
            province_data_tuple[3],
            # areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
            label_opts=opts.LabelOpts(is_show=False),
        )
            .set_global_opts(
            title_opts=opts.TitleOpts(title="新冠肺炎走勢圖"),
        )

    )
    # make_snapshot(snapshot, c, 'img/全國疫情視覺化line.gif')
    return c


def bar_datazoom_slider() -> Bar:
    from json_data import province_data_tuple
    c = (
        Bar(init_opts=opts.InitOpts(width='100%'))
        .add_xaxis(province_data_tuple[0])
        # 不顯示資料
        .add_yaxis("感染人數", province_data_tuple[1], label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(
            title_opts=opts.TitleOpts(title="新冠肺炎感染人數"),
            #  鎖定區域
            datazoom_opts=[opts.DataZoomOpts()],
        )
    )
    return c


def page_draggable_layout():
    page = Page(layout=Page.SimplePageLayout)
    page.add(
        get_map_old_data(),
        get_map_now_data(),
        get_line_pic(),
        bar_datazoom_slider(),
    )
    page.render('img/全國疫情視覺化彙總圖.html')
    # make_snapshot(snapshot, page.render(), '全國疫情視覺化.gif')


page_draggable_layout()

資料來源 sina api

# 封裝 json 資料類 返回所有需要的資料

# 新浪資料介面
# https://interface.sina.cn/news/wap/fymap2020_data.d.json

import json
import requests


class JsonData:

    # 獲取新浪api json 資料
    def get_sina_data(self):
        """

        :return:
        """
        # url = "https://interface.sina.cn/news/wap/fymap2020_data.d.json"
        # response = requests.request('get', url=url)
        # json_data = json.loads(response.text)
        with open('json.txt', 'r+') as f:
            json_text = f.read()
        json_data = json.loads(json_text)
        # print(json_data, type(json_data))
        return json_data['data']

    #  獲取地方名和累計人數
    def get_old_number(self):
        """

        :return: 各地區的 [名字和人數] 列表
        """
        province_data = []
        json_data = self.get_sina_data()['list']
        for one_data in json_data:
            # 獲取各地區名稱和感染人數
            province_data.append([
                one_data['name'],
                one_data['value']
            ])
        return province_data

    # 獲取當前新冠肺炎感染人數
    def get_now_number(self):
        province_data = []
        json_data = self.get_sina_data()['list']
        for one_data in json_data:
            # 獲取各地區名稱和當前感染人數
            province_data.append([
                one_data['name'],
                one_data['econNum']
            ])
        return province_data

    # 歷史資料 從 1.11 截止到2020年8月10日
    def get_history_list(self):
        json_data_history = self.get_sina_data()['historylist']
        date_x = []
        people_number_y = []
        people_cure_y = []
        people_death_y = []
        for data in json_data_history:
            date_x.append(data['date'])
            people_number_y.append(data['cn_conNum'])
            people_cure_y.append(data['cn_cureNum'])
            people_death_y.append(data['cn_deathNum'])
        return date_x[::-1], people_number_y[::-1], people_cure_y[::-1], people_death_y[::-1]


jsondata = JsonData()
province_data_sum = jsondata.get_old_number()  # 各個地區累計人數
province_data_now = jsondata.get_now_number()  # 各個地區當前人數
province_data_tuple = jsondata.get_history_list()