关于pyecharts可视化动态效果和美化布局中国经济、人口等数据

2022-03-11 14:33:23 浏览数 (1)

pyecharts提供了一些多坐标轴,图表组合功能,动画播放功能;

在本文中第一段代码是通过geo展现三千多个地级市、县级市的热力图,第二段代码是播放从1950年-2010年各省直辖市自治区GDP的发展情况;第三段代码是以表格方式展现六大行政区的一二三产业数据;第四段代码通过grid来调整标题和图例的布局,使报表更加美观;第五段代码是把4个报表在一个页面中展现出来。

代码示例

代码语言:javascript复制
i
import cx_Oracle
import pandas as pd
import os
import numpy as np
import random
from collections import OrderedDict
import json

from pyecharts import options as opts
from pyecharts.faker import Faker
from pyecharts.commons.utils import JsCode
from pyecharts.globals import SymbolType
from pyecharts.globals import ThemeType

from pyecharts.charts import Funnel,Gauge,Graph,Liquid,Parallel,Pie,Polar,Radar,Sankey,Sunburst,ThemeRiver,WordCloud,Gauge, Page,Timeline,Map,Geo
from pyecharts import options as opts
from pyecharts.charts import Page, ThemeRiver
from pyecharts.globals import ChartType, SymbolType

import json

username = 'metadata'
password = 'Wbq197711'
connstr ='127.0.0.1:1521/ORCL'
conn = cx_Oracle.connect(username,password,connstr) #连接数据库
sql='''
select b.areaname,b.echartprovincename,a.gdp
  from chinaeconomy a,proviceinfo b
 where a.provincename=b.provincename
   and a.reportyear=2010
 order by 1


with open(os.path.join("", "city_coordinates.json"), "r", encoding="utf-8") as f:
    j = json.load(f)
# {
#   "阿城": [
#     126.58,
#     45.32
#   ],
#   "阿克苏": [
#     80.19,
#     41.09
#   ],
# 生成全国城市的随机数组
provincename=['广东','江苏','山东','浙江','河南','河北','辽宁','四川','上海','湖南','重庆',
'湖北','福建','北京','安徽','陕西','广西','江西','天津','山西','吉林','云南',
'新疆','贵州','甘肃','海南','宁夏','青海','西藏','内蒙古','黑龙江']
citydatas=[[city,random.randrange(1,1000)] for city in j if city not in provincename]

def geo_heatmap() -> Geo:
    c = (
        Geo()
        .add_schema(maptype="china")
        .add(
            "geo",
            citydatas,
            type_=ChartType.HEATMAP,
        )
        .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(
            visualmap_opts=opts.VisualMapOpts(max_=2000),
            title_opts=opts.TitleOpts(title="Geo-HeatMap"),
        )
    )
    return c
c=geo_heatmap()
c.render('all_contry_city.html')
#
# print(citydatas)
# def map_visualmap() -> Map:
#     c = (
#         Map()
#         .add("商家A",citydatas, "china")
#         .set_global_opts(
#             title_opts=opts.TitleOpts(title="Map-VisualMap(连续型)"),
#             visualmap_opts=opts.VisualMapOpts(max_=1000),
#         )
#     )
#     return c
# c=map_visualmap()
# c.render('all_contry_city_map.html')

sql='''
select b.echartprovincename,a.reportyear,
       a.gdp    as population
  from chinaeconomy a,proviceinfo b
 where a.provincename=b.provincename
   and a.reportyear>=1952
 order by 2
 '''
df = pd.read_sql(sql,conn)  #read_sql读取数据
xdata=df['ECHARTPROVINCENAME'].tolist()
population=df['POPULATION'].round(2).tolist()  #四舍五入,再转list
reportyear=df['REPORTYEAR'].tolist()

minpopulation=min(population)
maxpopulation=max(population)
alldata=[list(z) for z in zip(reportyear,xdata, population)]

provicepiece=[{"min": 50000,  "label": ">=50000"},
              {"min": 20000, "max": 49999, "label": "20000 - 19999"},
              {"min": 10000, "max": 19999, "label": "10000 - 19999"},
              {"min": 5000, "max": 9999, "label": "5000 - 9999"},
              {"min": 2000, "max": 4999, "label": "2000 - 4999"},
              {"min": 1000, "max": 1999, "label": "1000 - 1999"},
              {"min": 500,"max": 999, "label": "500 - 999"},
              {"min": 200, "max": 499, "label": "200 - 499"},
              {"min": 100, "max": 199, "label": "100 - 199"},
              {"min": 50, "max": 99, "label": "50 - 99"},
              {"min": 20, "max": 49, "label": "20 - 49"},
              {"min": 10, "max": 19, "label": "10 - 19"},
              {"min": 5, "max": 9, "label": "5 - 9"},
              {"min": 1,"max": 4,  "label": "1 - 4"},
              {"max": 0, "label": "空缺"}
              ]
BAIDU_MAP_AK='ZMtqRARPIk09nUpWnNKSmMPBVpwTvsci'
def timeline_bmap() -> Timeline:
    tl = Timeline()
    tl.add_schema(pos_left="50%", pos_right="10px", pos_bottom="15px")
    for i in range(1952, 2010):
        bmap = (
        #     BMap()
        #     .add_schema(baidu_ak=BAIDU_MAP_AK, center=[120.13066322374, 30.240018034923])
        #     .add(
        #         "bmap",
        #         [[curdata[1], curdata[2]] for curdata in alldata if curdata[0] == i],
        #     )
        #     .set_global_opts(
        #         title_opts=opts.TitleOpts(title="Timeline-BMap-热力图-{}年".format(i)),
        #         visualmap_opts=opts.VisualMapOpts(max_=maxpopulation,is_piecewise=True,pieces=provicepiece,
        #             pos_bottom="center", pos_right="10px"
        #         ),
        #         tooltip_opts=opts.TooltipOpts(formatter=None),
        #     )
        # )
                Map()
                .add("商家A", [[curdata[1], curdata[2]] for curdata in alldata if curdata[0] == i], "china")
                .set_global_opts(
                    title_opts=opts.TitleOpts(title="Map-VisualMap(分段型)"),
                    visualmap_opts=opts.VisualMapOpts(max_=maxpopulation, is_piecewise=True,pieces=provicepiece),
                )
        )
        tl.add(bmap, "{}年".format(i))
    return tl
c=timeline_bmap()
c.render('timeline_bmap.html')

from pyecharts.components import Table
from pyecharts.options import ComponentTitleOpts

sql='''
select b.areaname,
       sum(a.importexportvalue) as importexportvalue,sum(a.exportvalue)/10000 as exportvalue,sum(a.importexportvalue-a.exportvalue)/10000 as importvalue
  from chinaeconomy a,proviceinfo b
 where a.provincename=b.provincename
   and a.reportyear=2010
 group by b.areaname
 order by 2
 '''
df = pd.read_sql(sql,conn)  #read_sql读取数据
headers=['行政区域','出口总额','进口总额','进出口总额']
xdata=df['AREANAME'].tolist()
exportvalue=df['EXPORTVALUE'].round(2).tolist()  #四舍五入,再转list
importvalue=df['IMPORTVALUE'].round(2).tolist()  #四舍五入,再转list
importexportvalue=df['IMPORTEXPORTVALUE'].round(2).tolist()  #四舍五入,再转list
datas=list(zip(xdata,exportvalue,importvalue,importexportvalue))
print(datas)
def table_base() -> Table:
    table = Table()

    #headers = ["City name", "Area", "Population", "Annual Rainfall"]
    rows = datas
    table.add(headers, rows).set_global_opts(
        title_opts=ComponentTitleOpts(title="Table-我是主标题", subtitle="我是副标题支持换行哦")
    )
    return table
c=table_base()
c.render('table_base.html')

from pyecharts.faker import Faker
from pyecharts import options as opts
from pyecharts.charts import Bar, Grid, Line,Scatter

# 主要通过grid来调整报表标题
def grid_base() -> Grid:
    c = (
        Bar()
        .add_xaxis(Faker.choose())
        .add_yaxis("商家A", Faker.values())
        .add_yaxis("商家B", Faker.values())
        .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题",
                                                   pos_left="center",  # 标题位置
                                                   pos_top="10%",
                                                   title_textstyle_opts=opts.TextStyleOpts(color="green", font_size=30),
                                                   ),
                            legend_opts = opts.LegendOpts(is_show=True, pos_right="10%", pos_top="10%", orient='vertical'))
    )

    grid=Grid()
    # 仅使用pos_top修改相对顶部的位置,标题和图表是分离的
    grid.add(c,grid_opts=opts.GridOpts(pos_top="30%"))
    return grid
c=grid_base()
c.render('grid_base.html')

def line_base() -> Line:
    c = (
        Line()
        .add_xaxis(Faker.choose())
        .add_yaxis("商家A", Faker.values())
        .add_yaxis("商家B", Faker.values())
        .set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例"))
    )
    return c

page = Page(layout=Page.SimplePageLayout)
# 需要自行调整每个 chart 的 height/width,显示效果在不同的显示器上可能不同
page.add(grid_base(), line_base(), timeline_bmap(),table_base())
page.render('DraggablePageLayout.html')

0 人点赞