pyecharts使用

时间:2024-08-31 22:07:20

安装

pyecharts 兼容 Python2 和 Python3。目前版本为 0.1.2

pip install pyecharts

入门

首先开始来绘制你的第一个图表

from pyecharts import Bar

bar = Bar("我的第一个图表", "这里是副标题")
bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [, , , , , ])
bar.show_config()
bar.render()
pyecharts使用

Tip: 可以按右边的下载按钮将图片下载到本地

  • add()
    主要方法,用于添加图表的数据和设置各种配置项
  • show_config()
    打印输出图表的所有配置项
  • render()
    默认将会在根目录下生成一个 render.html 的文件,支持 path 参数,设置文件保存位置,如 render(r"e:\my_first_chart.html"),文件用浏览器打开。
    默认的编码类型为 UTF-8,在 Python3 中是没什么问题的,Python3 对中文的支持好很多。但是在 Python2 中,编码的处理是个很头疼的问题,暂时没能找到完美的解决方法,目前只能通过文本编辑器自己进行二次编码,我用的是 Visual Studio Code,先通过 Gbk 编码重新打开,然后再用 UTF-8 重新保存,这样用浏览器打开的话就不会出现中文乱码问题了。

基本上所有的图表类型都是这样绘制的:

  1. chart_name = Type() 初始化具体类型图表。
  2. add() 添加数据及配置项。
  3. render() 生成 .html 文件。

Bar(柱状图/条形图)

from pyecharts import Bar

bar = Bar("标记线和标记点示例")
bar.add("商家A", attr, v1, mark_point=["average"])
bar.add("商家B", attr, v2, mark_line=["min", "max"])
bar.render()
pyecharts使用
from pyecharts import Bar

bar = Bar("x 轴和 y 轴交换")
bar.add("商家A", attr, v1)
bar.add("商家B", attr, v2, is_convert=True)
bar.render()
pyecharts使用

EffectScatter(带有涟漪特效动画的散点图)

from pyecharts import EffectScatter

v1 = [, , , , , ]
v2 = [, , , , , ]
es = EffectScatter("动态散点图示例")
es.add("effectScatter", v1, v2)
es.render()
pyecharts使用
es = EffectScatter("动态散点图各种图形示例")
es.add("", [], [], symbol_size=, effect_scale=3.5, effect_period=, symbol="pin")
es.add("", [], [], symbol_size=, effect_scale=4.5, effect_period=,symbol="rect")
es.add("", [], [], symbol_size=, effect_scale=5.5, effect_period=,symbol="roundRect")
es.add("", [], [], symbol_size=, effect_scale=6.5, effect_brushtype='fill',symbol="diamond")
es.add("", [], [], symbol_size=, effect_scale=5.5, effect_period=,symbol="arrow")
es.add("", [], [], symbol_size=, effect_scale=2.5, effect_period=,symbol="triangle")
es.render()
pyecharts使用

Funnel(漏斗图)

from pyecharts import Funnel

attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
value = [, , , , , ]
funnel = Funnel("漏斗图示例")
funnel.add("商品", attr, value, is_label_show=True, label_pos="inside", label_text_color="#fff")
funnel.render()
pyecharts使用

Gauge(仪表盘)

from pyecharts import Gauge

gauge = Gauge("仪表盘示例")
gauge.add("业务指标", "完成率", 66.66)
gauge.show_config()
gauge.render()
pyecharts使用

Geo(地理坐标系)

from pyecharts import Geo

data = [
("海门", ),("鄂尔多斯", ),("招远", ),("舟山", ),("齐齐哈尔", ),("盐城", ),
("赤峰", ),("青岛", ),("乳山", ),("金昌", ),("泉州", ),("莱西", ),
("日照", ),("胶南", ),("南通", ),("拉萨", ),("云浮", ),("梅州", )...]
geo = Geo("全国主要城市空气质量", "data from pm2.5", title_color="#fff", title_pos="center",
width=, height=, background_color='#404a59')
attr, value = geo.cast(data)
geo.add("", attr, value, visual_range=[, ], visual_text_color="#fff", symbol_size=, is_visualmap=True)
geo.show_config()
geo.render()
pyecharts使用
from pyecharts import Geo

data = [("海门", ), ("鄂尔多斯", ), ("招远", ), ("舟山", ), ("齐齐哈尔", ), ("盐城", )]
geo = Geo("全国主要城市空气质量", "data from pm2.5", title_color="#fff", title_pos="center",
width=, height=, background_color='#404a59')
attr, value = geo.cast(data)
geo.add("", attr, value, type="effectScatter", is_random=True, effect_scale=)
geo.show_config()
geo.render()
pyecharts使用

Graph(关系图)

from pyecharts import Graph

nodes = [{"name": "结点1", "symbolSize": },
{"name": "结点2", "symbolSize": },
{"name": "结点3", "symbolSize": },
{"name": "结点4", "symbolSize": },
{"name": "结点5", "symbolSize": },
{"name": "结点6", "symbolSize": },
{"name": "结点7", "symbolSize": },
{"name": "结点8", "symbolSize": }]
links = []
for i in nodes:
for j in nodes:
links.append({"source": i.get('name'), "target": j.get('name')})
graph = Graph("关系图-环形布局示例")
graph.add("", nodes, links, is_label_show=True, repulsion=, layout='circular', label_text_color=None)
graph.show_config()
graph.render()
pyecharts使用
from pyecharts import Graph

import json
with open("..\json\weibo.json", "r", encoding="utf-8") as f:
j = json.load(f)
nodes, links, categories, cont, mid, userl = j
graph = Graph("微博转发关系图", width=, height=)
graph.add("", nodes, links, categories, label_pos="right", repulsion=, is_legend_show=False,
line_curve=0.2, label_text_color=None)
graph.show_config()
graph.render()

Line(折线/面积图)

from pyecharts import Line

attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
v1 = [, , , , , ]
v2 = [, , , , , ]
line = Line("折线图示例")
line.add("商家A", attr, v1, mark_point=["average"])
line.add("商家B", attr, v2, is_smooth=True, mark_line=["max", "average"])
line.show_config()
line.render()
pyecharts使用
line = Line("折线图-阶梯图示例")
line.add("商家A", attr, v1, is_step=True, is_label_show=True)
line.show_config()
line.render()
pyecharts使用
line = Line("折线图-面积图示例")
line.add("商家A", attr, v1, is_fill=True, line_opacity=0.2, area_opacity=0.4, symbol=None)
line.add("商家B", attr, v2, is_fill=True, area_color='#000', area_opacity=0.3, is_smooth=True)
line.show_config()
line.render()


pyecharts使用

Liquid(水球图)

from pyecharts import Liquid

liquid = Liquid("水球图示例")
liquid.add("Liquid", [0.6])
liquid.show_config()
liquid.render()
pyecharts使用
from pyecharts import Liquid

liquid = Liquid("水球图示例")
liquid.add("Liquid", [0.6, 0.5, 0.4, 0.3], is_liquid_animation=False, shape='diamond')
liquid.show_config()
liquid.render()
pyecharts使用

Map(地图)

pyecharts使用
from pyecharts import Map

value = [, , , , ]
attr = ['汕头市', '汕尾市', '揭阳市', '阳江市', '肇庆市']
map = Map("广东地图示例", width=, height=)
map.add("", attr, value, maptype='广东', is_visualmap=True, visual_text_color='#000')
map.show_config()
map.render()
pyecharts使用
map-2

Parallel(平行坐标系)

from pyecharts import Parallel

c_schema = [
{"dim": , "name": "data"},
{"dim": , "name": "AQI"},
{"dim": , "name": "PM2.5"},
{"dim": , "name": "PM10"},
{"dim": , "name": "CO"},
{"dim": , "name": "NO2"},
{"dim": , "name": "CO2"},
{"dim": , "name": "等级",
"type": "category", "data": ['优', '良', '轻度污染', '中度污染', '重度污染', '严重污染']}
]
data = [
[, , , , 0.82, , , "良"],
[, , , , 0.86, , , "良"],
[, , , , 1.09, , , "良"],
[, , , , 1.28, , , "轻度污染"],
[, , , , 1.07, , , "轻度污染"],
[, , , , 1.28, , , "轻度污染"],
[, , , , 1.07, , , "轻度污染"],
[, , , , 0.86, , , "良"],
[, , , , 0.64, , , "良"],
[, , , , 1.01, , , "良"],
[, , , , 1.03, , , "轻度污染"],
[, , , , 1.1, , , "良"],
[, , , , 1.28, , , "良"],
[, , , , 1.47, , , "轻度污染"]
]
parallel = Parallel("平行坐标系-用户自定义指示器")
parallel.config(c_schema=c_schema)
parallel.add("parallel", data)
parallel.show_config()
parallel.render()
pyecharts使用

Pie(饼图)

from pyecharts import Pie

attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
v1 = [, , , , , ]
pie = Pie("饼图示例")
pie.add("", attr, v1, is_label_show=True)
pie.show_config()
pie.render()
pyecharts使用
from pyecharts import Pie

attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
v1 = [, , , , , ]
v2 = [, , , , , ]
pie = Pie("饼图-玫瑰图示例", title_pos='center', width=)
pie.add("商品A", attr, v1, center=[, ], is_random=True, radius=[, ], rosetype='radius')
pie.add("商品B", attr, v2, center=[, ], is_random=True, radius=[, ], rosetype='area',
is_legend_show=False, is_label_show=True)
pie.show_config()
pie.render()

Polar(极坐标系)

from pyecharts import Polar

radius = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
polar = Polar("极坐标系-堆叠柱状图示例", width=, height=)
polar.add("A", [, , , , , , ], radius_data=radius, type='barRadius', is_stack=True)
polar.add("B", [, , , , , , ], radius_data=radius, type='barRadius', is_stack=True)
polar.add("C", [, , , , , , ], radius_data=radius, type='barRadius', is_stack=True)
polar.show_config()
polar.render()
pyecharts使用
from pyecharts import Polar

radius = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
polar = Polar("极坐标系-堆叠柱状图示例", width=, height=)
polar.add("", [, , , , , , ], radius_data=radius, type='barAngle', is_stack=True)
polar.add("", [, , , , , , ], radius_data=radius, type='barAngle', is_stack=True)
polar.add("", [, , , , , , ], radius_data=radius, type='barAngle', is_stack=True)
polar.show_config()
polar.render()
pyecharts使用

Radar(雷达图)

from pyecharts import Radar

schema = [
("销售", ), ("管理", ), ("信息技术", ), ("客服", ), ("研发", ), ("市场", )]
v1 = [[, , , , , ]]
v2 = [[, , , , , ]]
radar = Radar()
radar.config(schema)
radar.add("预算分配", v1, is_splitline=True, is_axisline_show=True)
radar.add("实际开销", v2, label_color=["#4e79a7"], is_area_show=False)
radar.show_config()
radar.render()
pyecharts使用
value_bj = [
[, , , 0.46, , , ], [, , , 0.65, , , ],
[, , , 0.3, , , ], [, , , 0.33, , , ]...]
value_sh = [
[, , , 0.82, , , ], [, , , 0.86, , , ],
[, , , 1.09, , , ], [, , , 1.28, , , ]...]
c_schema= [{"name": "AQI", "max": , "min": },
{"name": "PM2.5", "max": , "min": },
{"name": "PM10", "max": , "min": },
{"name": "CO", "max": },
{"name": "NO2", "max": },
{"name": "SO2", "max": }]
radar = Radar()
radar.config(c_schema=c_schema, shape='circle')
radar.add("北京", value_bj, item_color="#f9713c", symbol=None)
radar.add("上海", value_sh, item_color="#b3e4a1", symbol=None)
radar.show_config()
radar.render()

Scatter(散点图)

from pyecharts import Scatter

v1 = [, , , , , ]
v2 = [, , , , , ]
scatter = Scatter("散点图示例")
scatter.add("A", v1, v2)
scatter.add("B", v1[::-], v2)
scatter.show_config()
scatter.render()
pyecharts使用
from pyecharts import Scatter

scatter = Scatter("散点图示例")
v1, v2 = scatter.draw("../images/pyecharts-0.png")
scatter.add("pyecharts", v1, v2, is_random=True)
scatter.show_config()
scatter.render()
pyecharts使用

WordCloud(词云图)

from pyecharts import WordCloud

name = ['Sam S Club', 'Macys', 'Amy Schumer', 'Jurassic World', 'Charter Communications',
'Chick Fil A', 'Planet Fitness', 'Pitch Perfect', 'Express', 'Home', 'Johnny Depp',
'Lena Dunham', 'Lewis Hamilton', 'KXAN', 'Mary Ellen Mark', 'Farrah Abraham',
'Rita Ora', 'Serena Williams', 'NCAA baseball tournament', 'Point Break']
value = [, , , , , , , , , , , , ,
, , , , , , ]
wordcloud = WordCloud(width=, height=)
wordcloud.add("", name, value, word_size_range=[, ])
wordcloud.show_config()
wordcloud.render()
pyecharts使用

用户自定义

用户还可以自定义结合 Line/Bar 图表
需使用 get_series()custom() 方法

get_series()
""" 获取图表的 series 数据 """ custom(series)
''' 追加自定义图表类型 '''
  • series -> dict
    追加图表类型的 series 数据

先用 get_series() 获取数据,再使用 custom() 将图表结合在一起

from pyecharts import Bar, Line

attr = ['A', 'B', 'C', 'D', 'E', 'F']
v1 = [, , , , , ]
v2 = [, , , , , ]
v3 = [, , , , , ]
bar = Bar("Line - Bar 示例")
bar.add("bar", attr, v1)
line = Line()
line.add("line", v2, v3)
bar.custom(line.get_series())
bar.show_config()
bar.render()
pyecharts使用

更多示例

用极坐标系画出一个爱心

import math
from pyecharts import Polar data = []
for i in range():
theta = i / *
r = * ( + math.sin(theta / * math.pi))
data.append([r, theta])
hour = [i for i in range(, )]
polar = Polar("极坐标系示例", width=, height=)
polar.add("Love", data, angle_data=hour, boundary_gap=False,start_angle=)
polar.show_config()
polar.render()
pyecharts使用

用极坐标系画出一朵小花

import math
from pyecharts import Polar data = []
for i in range():
t = i / * math.pi
r = math.sin( * t) * math.cos( * t)
data.append([r, i])
polar = Polar("极坐标系示例", width=, height=)
polar.add("Flower", data, start_angle=, symbol=None, axis_range=[, None])
polar.show_config()
polar.render()
pyecharts使用

还可以给小花涂上颜色

import math
from pyecharts import Polar data = []
for i in range():
t = i / * math.pi
r = math.sin( * t) * math.cos( * t)
data.append([r, i])
polar = Polar("极坐标系示例", width=, height=)
polar.add("Color-Flower", data, start_angle=, symbol=None, axis_range=[, None],
area_color="#f71f24", area_opacity=0.6)
polar.show_config()
polar.render()
pyecharts使用

用散点图画出一个爱心

from pyecharts import Scatter

scatter = Scatter("散点图示例", width=, height=)
v1 ,v2 = scatter.draw("../images/love.png")
scatter.add("Love", v1, v2)
scatter.render()
pyecharts使用

用散点图画出一个火辣的 Bra

from pyecharts import Scatter

scatter = Scatter("散点图示例", width=, height=)
v1 ,v2 = scatter.draw("../images/cup.png")
scatter.add("Cup", v1, v2)
scatter.render()
pyecharts使用

用散点图画出一个性感的 Bra

from pyecharts import Scatter

scatter = Scatter("散点图示例", width=, height=)
v1 ,v2 = scatter.draw("../images/cup.png")
scatter.add("Cup", v1, v2, label_color=["#000"])
scatter.render()
pyecharts使用

某地最低温和最高气温折线图

from pyecharts import Line

attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日', ]
line = Line("折线图示例")
line.add("最高气温", attr, [, , , , , , ], mark_point=["max", "min"], mark_line=["average"])
line.add("最低气温", attr, [, -, , , , , ], mark_point=["max", "min"],
mark_line=["average"], yaxis_formatter="°C")
line.show_config()
line.render()
pyecharts使用

饼图嵌套

from pyecharts import Pie

pie = Pie("饼图示例", title_pos='center', width=, height=)
pie.add("", ['A', 'B', 'C', 'D', 'E', 'F'], [, , , , , ], radius=[, ],is_label_show=True)
pie.add("", ['H', 'I', 'J'], [, , ], radius=[, ], legend_orient='vertical', legend_pos='left')
pie.show_config()
pie.render()
pyecharts使用

饼图再嵌套

import random
from pyecharts import Pie attr = ['A', 'B', 'C', 'D', 'E', 'F']
pie = Pie("饼图示例", width=, height=)
pie.add("", attr, [random.randint(, ) for _ in range()], radius=[, ], center=[, ],is_random=True)
pie.add("", attr, [random.randint(, ) for _ in range()], radius=[, ], center=[, ],rosetype='area')
pie.add("", attr, [random.randint(, ) for _ in range()], radius=[, ], center=[, ],is_random=True)
pie.add("", attr, [random.randint(, ) for _ in range()], radius=[, ], center=[, ],rosetype='radius')
pie.show_config()
pie.render()
pyecharts使用

某地的降水量和蒸发量柱状图

from pyecharts import Bar

attr = ["{}月".format(i) for i in range(, )]
v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
bar = Bar("柱状图示例")
bar.add("蒸发量", attr, v1, mark_line=["average"], mark_point=["max", "min"])
bar.add("降水量", attr, v2, mark_line=["average"], mark_point=["max", "min"])
bar.show_config()
bar.render()
pyecharts使用

各类电影中"好片"所占的比例

from pyecharts import Pie

pie = Pie('各类电影中"好片"所占的比例', "数据来着豆瓣", title_pos='center')
pie.add("", ["剧情", ""], [, ], center=[, ], radius=[, ],
label_pos='center', is_label_show=True, label_text_color=None, )
pie.add("", ["奇幻", ""], [, ], center=[, ], radius=[, ],
label_pos='center', is_label_show=True, label_text_color=None, legend_pos='left')
pie.add("", ["爱情", ""], [, ], center=[, ], radius=[, ],
label_pos='center', is_label_show=True, label_text_color=None)
pie.add("", ["惊悚", ""], [, ], center=[, ], radius=[, ],
label_pos='center', is_label_show=True, label_text_color=None)
pie.add("", ["冒险", ""], [, ], center=[, ], radius=[, ],
label_pos='center', is_label_show=True, label_text_color=None)
pie.add("", ["动作", ""], [, ], center=[, ], radius=[, ],
label_pos='center', is_label_show=True, label_text_color=None)
pie.add("", ["喜剧", ""], [, ], center=[, ], radius=[, ],
label_pos='center', is_label_show=True, label_text_color=None)
pie.add("", ["科幻", ""], [, ], center=[, ], radius=[, ],
label_pos='center', is_label_show=True, label_text_color=None)
pie.add("", ["悬疑", ""], [, ], center=[, ], radius=[, ],
label_pos='center', is_label_show=True, label_text_color=None)
pie.add("", ["犯罪", ""], [, ], center=[, ], radius=[, ],
label_pos='center', is_label_show=True, label_text_color=None, is_legend_show=True, legend_top="center")
pie.show_config()
pie.render()
pyecharts使用

用极坐标系画出一个蜗牛壳

import math
from pyecharts import Polar data = []
for i in range():
for j in range():
theta = j / *
alpha = i * + theta
r = math.pow(math.e, 0.003 * alpha)
data.append([r, theta])
polar = Polar("极坐标系示例")
polar.add("", data, symbol_size=, symbol='circle', start_angle=-, is_radiusaxis_show=False,
area_color="#f3c5b3", area_opacity=0.5, is_angleaxis_show=False)
polar.show_config()
polar.render()
pyecharts使用