pyechart也提供了一些树型图表和地理图表,树型图表又包括树图和矩型树图;地理图表MAP、GEO、BMAP等图表;其中树图意义不大,矩形树图难度在对json格式的处理上,把sql转为pandas再转为groupby分组再转为嵌套json;地理图表的geo图表主要是点状和热力图,适合定性分析,map是面状的,适合量化分析,bmap则和百度地图结合的更紧凑,学习难度较大。
如下:
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,TreeMap,BMap
# theme 定制图表样式,共内置15种
# ThemeType.WHITE|ThemeType.LIGHT|ThemeType.DARK|ThemeType.CHALK|ThemeType.ESSOS|
# ThemeType.INFOGRAPHIC|ThemeType.MACARONS|ThemeType.PURPLE_PASSION|ThemeType.ROMA|ThemeType.ROMANTIC|
# ThemeType.SHINE|ThemeType.VINTAGE|ThemeType.WALDEN|ThemeType.WESTEROS|Type.WONDERLAND
# 全局配置项
# InitOpts:初始化配置项
# TitleOpts:标题配置项
# AnimationOpts:Echarts 画图动画配置项
# ToolBoxFeatureOpts:工具箱工具配置项
# ToolboxOpts:工具箱配置项
# BrushOpts:区域选择组件配置项
# DataZoomOpts:区域缩放配置项
# LegendOpts:图例配置项
# VisualMapOpts:视觉映射配置项
# TooltipOpts:提示框配置项
# AxisLineOpts: 坐标轴轴线配置项
# AxisTickOpts: 坐标轴刻度配置项
# AxisPointerOpts: 坐标轴指示器配置项
# AxisOpts:坐标轴配置项
# SingleAxisOpts:单轴配置项
# GraphicGroup:原生图形元素组件
# 系列配置项
# ItemStyleOpts:图元样式配置项
# TextStyleOpts:文字样式配置项
# LabelOpts:标签配置项
# LineStyleOpts:线样式配置项
# SplitLineOpts:分割线配置项
# MarkPointItem:标记点数据项
# MarkPointOpts:标记点配置项
# MarkLineItem:标记线数据项
# MarkLineOpts:标记线配置项
# MarkAreaItem: 标记区域数据项
# MarkAreaOpts: 标记区域配置项
# EffectOpts:涟漪特效配置项
# AreaStyleOpts:区域填充样式配置项
# SplitAreaOpts:分隔区域配置项
'''
数据情况,考虑到pandas对数据处理的不便,还是使用了标准的数据库方式
------------------------------------------------------
表名称:chinaeconomy 中国各省市自治区1950-2010年总体情况表
REPORTYEAR 年度
PROVINCEID 省市编号
PROVINCENAME 省市名称
GDP 地区国内生产总值(亿元)
EVERAGEGDP 人均国内生产总值(元)
PRIMARYINDUSTRYVALUE 各地区第一产业增加值(亿元)
SECONDINDUSTRYVALUE 各地区第二产业增加值(亿元)
THIRDINDUSTRYVALUE 各地区第三产业增加值(亿元)
IMPORTEXPORTVALUE 进出口总额(万美元)
EXPORTVALUE 出口总额(万美元)
POPULATION 年底总人口数(万人)
BIRTHRATE 人口出生率(‰)
DEADRATE 人口死亡率(‰)
GROWTHRATE 人口自然增长率(‰)
------------------------------------------------------
表名称:provinceinfo 中国各省市自治区对应echart中的省市自治区简写和行政区域
PROVINCENAME 省市名称
ECHARTPROVINCENAME echart省市名称
AREANAME 行政区划
------------------------------------------------------
基本SQL语句
select b.areaname,b.echartprovincename,a.reportyear,
a.gdp,a.everagegdp,
a.primaryindustryvalue,a.secondindustryvalue,a.thirdindustryvalue,
a.importexportvalue,a.exportvalue,
a.population,a.birthrate,a.deadrate,a.growthrate
from chinaeconomy a,proviceinfo b
where a.provincename=b.provincename
'''
# 初始化
username = 'metadata'
password = 'XXXX'
connstr ='127.0.0.1:1521/ORCL'
conn = cx_Oracle.connect(username,password,connstr) #连接数据库
provicepiece=[{"min": 40000, "label": ">= 40000"},
{"min": 20000,"max": 39999, "label": "20000 - 39999"},
{"min": 10000,"max": 19999, "label": "10000 - 19999"},
{"min": 5000,"max": 9999, "label": "5000 - 9999"},
{"min": 1,"max": 4999, "label": "1 - 4999"}
]
sql='''
select b.areaname,b.echartprovincename echartprovincename,a.gdp gdp
from chinaeconomy a,proviceinfo b
where a.provincename=b.provincename
and a.reportyear=2010
order by 1
'''
df = pd.read_sql(sql,conn) #read_sql读取数据
results = []
# 按areaname分组,分别获取分组值和分组的子数据
for (areaname), bag in df.groupby(["AREANAME"]):
areagdp=bag['GDP'].sum() #对当前分组值内的GDP进行计算
contents_df = bag.drop(["AREANAME"], axis=1) #重新格式化分组值内的数据,删除areaname列
children = [OrderedDict(value=row[1],name=row[0]) for i,row in contents_df.iterrows()] #生成子节点列表
results.append(OrderedDict([("value", areagdp),("name", areaname),("children", children)])) #生成字典,字典包括父节点和子节点信息
#将结果写入json文件
with open('areaprovincetree.json', 'w', encoding="utf-8") as outfile:
outfile.write(json.dumps(results, indent=4))
# TreeMap:矩形树图
def treemap_gdp() -> TreeMap:
with open(os.path.join("", "areaprovincetree.json"), "r", encoding="utf-8") as f:
data = json.load(f)
c = (
TreeMap()
.add("演示数据", data)
.set_global_opts(title_opts=opts.TitleOpts(title="TreeMap-基本示例"))
)
return c
c=treemap_gdp()
c.render('treemap_gdp.html')
from pyecharts.faker import Faker
from pyecharts import options as opts
from pyecharts.charts import Geo
from pyecharts.globals import ChartType, SymbolType
sql='''
select b.echartprovincename,
a.gdp as population
from chinaeconomy a,proviceinfo b
where a.provincename=b.provincename
and a.reportyear=2010
order by 2
'''
df = pd.read_sql(sql,conn) #read_sql读取数据
xdata=df['ECHARTPROVINCENAME'].tolist()
population=df['POPULATION'].round(2).tolist() #四舍五入,再转list
print(xdata)
print(population)
minpopulation=min(population)
maxpopulation=max(population)
print(minpopulation,maxpopulation)
def geo_base() -> Geo:
c = (
Geo()
.add_schema(maptype="china")
.add("geo", [list(z) for z in zip(xdata, population)])
.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
.set_global_opts(
visualmap_opts=opts.VisualMapOpts(),
title_opts=opts.TitleOpts(title="Geo-基本示例"),
)
)
return c
c=geo_base()
c.render('geo_base.html')
def geo_visualmap_piecewise() -> Geo:
c = (
Geo()
.add_schema(maptype="china")
.add("geo", [list(z) for z in zip(xdata, population)])
.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
.set_global_opts(
visualmap_opts=opts.VisualMapOpts(max_=maxpopulation, is_piecewise=True,pieces=provicepiece),
title_opts=opts.TitleOpts(title="Geo-VisualMap(分段型)"),
)
)
return c
c=geo_visualmap_piecewise()
c.render('geo_visualmap_piecewise.html')
def geo_effectscatter() -> Geo:
c = (
Geo()
.add_schema(maptype="china")
.add(
"geo",
[list(z) for z in zip(xdata, population)],
type_=ChartType.EFFECT_SCATTER,
)
.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
.set_global_opts(title_opts=opts.TitleOpts(title="Geo-EffectScatter"))
)
return c
c=geo_effectscatter()
c.render('geo_effectscatter.html')
def geo_piece_effectscatter() -> Geo:
c = (
Geo()
.add_schema(maptype="china")
.add(
"geo",
[list(z) for z in zip(xdata, population)],
type_=ChartType.EFFECT_SCATTER,
)
.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
.set_global_opts(title_opts=opts.TitleOpts(title="Geo-EffectScatter"),
visualmap_opts=opts.VisualMapOpts(max_=maxpopulation,is_piecewise=True,pieces=provicepiece),)
#visualmap_opts=opts.VisualMapOpts(type_="size", max_=maxpopulation, is_piecewise=True, pieces=provicepiece),)
)
return c
c=geo_piece_effectscatter()
c.render('geo_piece_effectscatter.html')
def geo_heatmap() -> Geo:
c = (
Geo()
.add_schema(maptype="china")
.add(
"geo",
[list(z) for z in zip(xdata, population)],
type_=ChartType.HEATMAP,
)
.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
.set_global_opts(
visualmap_opts=opts.VisualMapOpts(),
title_opts=opts.TitleOpts(title="Geo-HeatMap"),
)
)
return c
c=geo_heatmap()
c.render('geo_heatmap.html')
areainfo=list(zip(xdata,population))
sourcetarget=[('广东',i) for i in xdata if i!='广东']
def geo_lines_background() -> Geo:
c = (
Geo()
.add_schema(
maptype="china",
itemstyle_opts=opts.ItemStyleOpts(color="#323c48", border_color="#111"),
)
.add(
"",
areainfo,
type_=ChartType.EFFECT_SCATTER,
color="white",
)
.add(
"geo",
sourcetarget,
type_=ChartType.LINES,
effect_opts=opts.EffectOpts(
symbol=SymbolType.ARROW, symbol_size=6, color="blue"
),
linestyle_opts=opts.LineStyleOpts(curve=0.2),
)
.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
.set_global_opts(title_opts=opts.TitleOpts(title="Geo-Lines-background"))
)
return c
c=geo_lines_background()
c.render('geo_lines_background.html')
from pyecharts import options as opts
from pyecharts.charts import Map
mapdata=[list(z) for z in zip(xdata, population)]
def map_base() -> Map:
c = (
Map()
.add("商家A", mapdata, "china")
.set_global_opts(title_opts=opts.TitleOpts(title="Map-基本示例"))
)
return c
c=map_base()
c.render('map_base.html')
def map_without_label() -> Map:
c = (
Map()
.add("商家A", mapdata, "china")
.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
.set_global_opts(title_opts=opts.TitleOpts(title="Map-不显示Label"))
)
return c
c=map_without_label()
c.render('map_without_label.html')
def map_visualmap() -> Map:
c = (
Map()
.add("商家A", mapdata, "china")
.set_global_opts(
title_opts=opts.TitleOpts(title="Map-VisualMap(连续型)"),
visualmap_opts=opts.VisualMapOpts(max_=200),
)
)
return c
c=map_visualmap()
c.render('map_visualmap.html')
def map_visualmap() -> Map:
c = (
Map()
.add("商家A",mapdata, "china")
.set_global_opts(
title_opts=opts.TitleOpts(title="Map-VisualMap(分段型)"),
visualmap_opts=opts.VisualMapOpts(max_=maxpopulation, is_piecewise=True,pieces=provicepiece),
)
)
return c
c=map_visualmap()
c.render('map_visualmap.html')
BAIDU_MAP_AK='ZMtqRARPIk09nUpWnNKSmMPBVpwTvsci'
def bmap_heatmap() -> BMap:
c = (
BMap()
.add_schema(baidu_ak=BAIDU_MAP_AK, center=[120.13066322374, 30.240018034923])
.add(
"bmap",
mapdata,
type_="heatmap",
label_opts=opts.LabelOpts(formatter="{b}"),
)
.set_global_opts(
title_opts=opts.TitleOpts(title="BMap-热力图"),
visualmap_opts=opts.VisualMapOpts(),
)
)
return c
c=bmap_heatmap()
c.render('bmap_heatmap.html')
长按二维码关注“追梦IT人”