首先我们了解一下pie.py,下面代码中为add()函数增加了注释,方便在调用add()函数绘制饼图时参考:
from ... import options as optsfrom ... import typesfrom ...charts.chart import Chartfrom ...globals import ChartTypeclass Pie(Chart): # 定义pie图的类"""<<< Pie >>>The pie chart is mainly used to represent the proportion of data ofdifferent categories in the total. Each radian represents the ratio ofthe number of data points."""def add(self,series_name: str, # 序列名:参数为字符串类型data_pair: types.Sequence, # 数值对:序列类型,格式为[(key1,value1),(key2,value2)...]*,color: types.Optional[str] = None, # 系列标签颜色radius: types.Optional[types.Sequence] = None, # 饼图半径,数组的第一项是内半径,第二项是外半径,默认设置成百分比,相对于容器高宽中较小的一项的一半center: types.Optional[types.Sequence] = None, # 圆心坐标,数组的第一项是横坐标,第二项是纵坐标,默认设置成百分比,设置成百分比时,第一项是相对于容器的宽度,第二项是相对于容器的高度rosetype: types.Optional[str] = None, # 是否展示为南丁格尔玫瑰图模式,通过半径区分数据的大小,有'radius'和'area'两种模式,'radius'扇区圆心角展现的数据的百分比,半径展现数据的大小;'area'所有扇区圆心角相同,仅通过半径展现数据的大小is_clockwise: bool = True, # 饼图的扇区是否是顺时针排布label_opts: types.Label = opts.LabelOpts(), # 标签配置项,参考'series_options.LabelOpts'tooltip_opts: types.Tooltip = None, # 提示框组件配置项,参考'series_options.TooltipOpts'itemstyle_opts: types.ItemStyle = None, # 图元样式配置项,参考'series_options.ItemStyleOpts'): # 定义add函数data = [{"name": n, "value": v} for n, v in data_pair]# 生成数据的键值对if not radius:radius = ["0%", "75%"]if not center:center = ["50%", "50%"]self._append_color(color)for a, _ in data_pair:self.options.get("legend")[0].get("data").append(a)_dlst = self.options.get("legend")[0].get("data")_dset = list(set(_dlst))_dset.sort(key=_dlst.index)self.options.get("legend")[0].update(data=list(_dset))self.options.get("series").append({"type": ChartType.PIE,"name": series_name,"clockwise": is_clockwise,"data": data,"radius": radius,"center": center,"roseType": rosetype,"label": label_opts,"tooltip": tooltip_opts,"itemStyle": itemstyle_opts,})return self
Pie - Pie_base
pyecharts 代码
from pyecharts import options as opts
from pyecharts.charts import Pie
import random
animal = ["河马", "蟒蛇", "老虎", "大象", "兔子", "熊猫", "狮子"]
values = [random.randint(20, 150) for i in range(7)] # 随机产生比例
print(values) # [96, 65, 139, 32, 44, 79, 73]
ls = [list(z) for z in zip(animal, values)] # 组合
print(ls) # [['河马', 96], ['蟒蛇', 65], ['老虎', 139], ['大象', 32], ['兔子', 44], ['熊猫', 79], ['狮子', 73]]
c = (
Pie()
# .add("", [list(z) for z in zip(Faker.choose(), Faker.values())])
.add("", ls)
.set_global_opts(title_opts=opts.TitleOpts(title="Pie-基本示例"))
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
.render("pie_base.html")
)
pyecharts 效果
Pie - Pie_position
pyecharts 代码
from pyecharts import options as opts
from pyecharts.charts import Pie
import random
animal = ["河马", "蟒蛇", "老虎", "大象", "兔子", "熊猫", "狮子"]
values = [random.randint(20, 150) for i in range(7)] # 随机产生比例
print(values) # [113, 72, 47, 106, 84, 76, 22]
ls = [list(z) for z in zip(animal, values)] # 组合
print(ls) # [['河马', 113], ['蟒蛇', 72], ['老虎', 47], ['大象', 106], ['兔子', 84], ['熊猫', 76], ['狮子', 22]]
c = (
Pie()
.add(
"",
ls,
# [list(z) for z in zip(Faker.choose(), Faker.values())],
center=["35%", "50%"],
)
.set_global_opts(
title_opts=opts.TitleOpts(title="Pie-调整位置"),
legend_opts=opts.LegendOpts(pos_left="15%"),
)
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}")) # 河马:113
.render("pie_position.html")
)
pyecharts 效果
Pie - Pie_scroll_legend
clothes = ["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"]
drinks = ["可乐", "雪碧", "橙汁", "绿茶", "奶茶", "百威", "青岛"]
phones = ["小米", "三星", "华为", "苹果", "魅族", "VIVO", "OPPO"]
fruits = ["草莓", "芒果", "葡萄", "雪梨", "西瓜", "柠檬", "车厘子"]
animal = ["河马", "蟒蛇", "老虎", "大象", "兔子", "熊猫", "狮子"]
cars = ["宝马", "法拉利", "奔驰", "奥迪", "大众", "丰田", "特斯拉"]
dogs = ["哈士奇", "萨摩耶", "泰迪", "金毛", "牧羊犬", "吉娃娃", "柯基"]
week = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
week_en = "Saturday Friday Thursday Wednesday Tuesday Monday Sunday".split()
clock = ( "12a 1a 2a 3a 4a 5a 6a 7a 8a 9a 10a 11a 12p " "1p 2p 3p 4p 5p 6p 7p 8p 9p 10p 11p".split() )
pyecharts 代码
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.faker import Faker
c = (
Pie()
.add(
"",
[
list(z)
for z in zip(
Faker.choose() + Faker.choose() + Faker.choose(), # Faker中取三组
Faker.values() + Faker.values() + Faker.values(), # 随机生成三组值
)
],
center=["40%", "50%"],
)
.set_global_opts(
title_opts=opts.TitleOpts(title="Pie-Legend 滚动"),
legend_opts=opts.LegendOpts(type_="scroll", pos_left="80%", orient="vertical"), # 滚动出现
)
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
.render("pie_scroll_legend.html")
)
pyecharts 效果
Pie - Pie_set_color
from pyecharts import options as opts
from pyecharts.charts import Pie
import random
drinks = ["可乐", "雪碧", "橙汁", "绿茶", "奶茶", "百威", "青岛"] # 品牌列表
values = [random.randint(20, 150) for i in range(7)] # 随机产生比例
ls = [list(z) for z in zip(drinks, values)] # 组合
# [['可乐', 56], ['雪碧', 24], ['橙汁', 82], ['绿茶', 22], ['奶茶', 107], ['百威', 53], ['青岛', 32]]
c = (
Pie()
.add("",ls )
.set_colors(["blue", "green", "yellow", "red", "pink", "orange", "purple"])
.set_global_opts(title_opts=opts.TitleOpts(title="Pie-设置颜色"))
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
.render("pie_set_color.html") # 渲染饼图并保存成html文件
)

官方示例中的数据来自faker.pyfaker.py下面给出部分内容
class _Faker:
clothes = ["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"]
drinks = ["可乐", "雪碧", "橙汁", "绿茶", "奶茶", "百威", "青岛"]
phones = ["小米", "三星", "华为", "苹果", "魅族", "VIVO", "OPPO"]
fruits = ["草莓", "芒果", "葡萄", "雪梨", "西瓜", "柠檬", "车厘子"]
animal = ["河马", "蟒蛇", "老虎", "大象", "兔子", "熊猫", "狮子"]
cars = ["宝马", "法拉利", "奔驰", "奥迪", "大众", "丰田", "特斯拉"]
dogs = ["哈士奇", "萨摩耶", "泰迪", "金毛", "牧羊犬", "吉娃娃", "柯基"]
week = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
week_en = "Saturday Friday Thursday Wednesday Tuesday Monday Sunday".split()
clock = (
"12a 1a 2a 3a 4a 5a 6a 7a 8a 9a 10a 11a 12p "
"1p 2p 3p 4p 5p 6p 7p 8p 9p 10p 11p".split()
)
@staticmethod
def values(start: int = 20, end: int = 150) -> list:
return [random.randint(start, end) for _ in range(7)]
Faker = _Faker()
官方示例中应用到来自于faker中的数据
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.faker import Faker
c = (
Pie()
.add("", [list(z) for z in zip(Faker.choose(), Faker.values())])
.set_colors(["blue", "green", "yellow", "red", "pink", "orange", "purple"])
.set_global_opts(title_opts=opts.TitleOpts(title="Pie-设置颜色"))
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
.render("pie_set_color.html")
)
Pie - Doughnut_chart
pyecharts 代码
import pyecharts.options as opts
from pyecharts.charts import Pie
"""
Gallery 使用 pyecharts 1.1.0
参考地址: https://echarts.baidu.com/examples/editor.html?c=pie-doughnut
目前无法实现的功能:
1、饼状图中间的图例名称暂时无法显示
"""
x_data = ["直接访问", "邮件营销", "联盟广告", "视频广告", "搜索引擎"]
y_data = [335, 310, 234, 135, 1548]
(
Pie(init_opts=opts.InitOpts(width="1000px", height="600px"))
.add(
series_name="访问来源",
data_pair=[list(z) for z in zip(x_data, y_data)],
radius=["50%", "70%"],
label_opts=opts.LabelOpts(is_show=False, position="center"),
)
.set_global_opts(legend_opts=opts.LegendOpts(pos_left="legft", orient="vertical"))
.set_series_opts(
tooltip_opts=opts.TooltipOpts(
trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)"
),
label_opts=opts.LabelOpts(formatter="{b}: {c}")
)
.render("doughnut_chart.html")
)
pyecharts 效果
Pie - Pie_radius
pyecharts 代码
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.faker import Faker
c = (
Pie()
.add(
"",
[list(z) for z in zip(Faker.choose(), Faker.values())],
radius=["40%", "75%"],
)
.set_global_opts(
title_opts=opts.TitleOpts(title="Pie-Radius"),
legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"),
)
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
.render("pie_radius.html")
)
pyecharts 效果
富文本标签
pyecharts 代码
from pyecharts import options as opts
from pyecharts.charts import Pie
import random
animal = ["河马", "蟒蛇", "老虎", "大象", "兔子", "熊猫", "狮子"]
values = [random.randint(20, 150) for i in range(7)] # 随机产生比例
print(values) # [89, 91, 33, 73, 49, 87, 93]
ls = [list(z) for z in zip(animal, values)] # 组合
print(ls) # [['河马', 89], ['蟒蛇', 91], ['老虎', 33], ['大象', 73], ['兔子', 49], ['熊猫', 87], ['狮子', 93]]
c = (
Pie()
.add(
"",
ls,
radius=["40%", "55%"], # 内径、外径
label_opts=opts.LabelOpts(
position="outside",
formatter="{a|{a}}{abg|}\n{hr|}\n {b|{b}: }{c} {per|{d}%} ", # series 0 河马:89 17.28%
background_color="#eee", # 背景色
border_color="#aaa", # 边框色
border_width=1, # 边框宽度
border_radius=4,
rich={ # 设置标签文本颜色、背景色、字体、字号、位置等
"a": {"color": "#999", "lineHeight": 22, "align": "center"},
"abg": {
"backgroundColor": "#e3e3e3",
"width": "100%",
"align": "right",
"height": 22,
"borderRadius": [4, 4, 0, 0],
},
"hr": {
"borderColor": "#aaa",
"width": "100%",
"borderWidth": 0.5,
"height": 0,
},
"b": {"fontSize": 16, "lineHeight": 33},
"per": {
"color": "#eee",
"backgroundColor": "#334455",
"padding": [2, 4],
"borderRadius": 2,
},
},
),
)
.set_global_opts(title_opts=opts.TitleOpts(title="Pie-富文本示例"))
.render("pie_rich_label.html")
)
pyecharts 效果

Pie - Nested_pies
pyecharts 代码
import pyecharts.options as opts
from pyecharts.charts import Pie
"""
Gallery 使用 pyecharts 1.1.0
参考地址: https://echarts.baidu.com/examples/editor.html?c=pie-nest
目前无法实现的功能:
1、暂无
"""
inner_x_data = ["直达", "营销广告", "搜索引擎"]
inner_y_data = [335, 679, 1548]
inner_data_pair = [list(z) for z in zip(inner_x_data, inner_y_data)]
outer_x_data = ["直达", "营销广告", "搜索引擎", "邮件营销", "联盟广告", "视频广告", "百度", "谷歌", "必应", "其他"]
outer_y_data = [335, 310, 234, 135, 1048, 251, 147, 102]
outer_data_pair = [list(z) for z in zip(outer_x_data, outer_y_data)]
(
Pie(init_opts=opts.InitOpts(width="1000px", height="600px"))
.add(
series_name="访问来源",
data_pair=inner_data_pair,
radius=[0, "30%"],
label_opts=opts.LabelOpts(position="inner"),
)
.add(
series_name="访问来源",
radius=["40%", "55%"],
data_pair=outer_data_pair,
label_opts=opts.LabelOpts(
position="outside",
formatter="{a|{a}}{abg|}\n{hr|}\n {b|{b}: }{c} {per|{d}%} ",
background_color="#eee",
border_color="#aaa",
border_width=1,
border_radius=4,
rich={
"a": {"color": "#999", "lineHeight": 22, "align": "center"},
"abg": {
"backgroundColor": "#e3e3e3",
"width": "100%",
"align": "right",
"height": 22,
"borderRadius": [4, 4, 0, 0],
},
"hr": {
"borderColor": "#aaa",
"width": "100%",
"borderWidth": 0.5,
"height": 0,
},
"b": {"fontSize": 16, "lineHeight": 33},
"per": {
"color": "#eee",
"backgroundColor": "#334455",
"padding": [2, 4],
"borderRadius": 2,
},
},
),
)
.set_global_opts(legend_opts=opts.LegendOpts(pos_left="left", orient="vertical"))
.set_series_opts(
tooltip_opts=opts.TooltipOpts(
trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)"
)
)
.render("nested_pies.html")
)
pyecharts 效果

Pie - Mutiple_pie
pyecharts 代码
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.commons.utils import JsCode
fn = """
function(params) {
if(params.name == '其他')
return '\\n\\n\\n' + params.name + ' : ' + params.value + '%';
return params.name + ' : ' + params.value + '%';
}
"""
def new_label_opts():
return opts.LabelOpts(formatter=JsCode(fn), position="center")
c = (
Pie()
.add(
"",
[list(z) for z in zip(["剧情", "其他"], [25, 75])],
center=["20%", "30%"],
radius=[60, 80],
label_opts=new_label_opts(),
)
.add(
"",
[list(z) for z in zip(["奇幻", "其他"], [24, 76])],
center=["55%", "30%"],
radius=[60, 80],
label_opts=new_label_opts(),
)
.add(
"",
[list(z) for z in zip(["爱情", "其他"], [14, 86])],
center=["20%", "70%"],
radius=[60, 80],
label_opts=new_label_opts(),
)
.add(
"",
[list(z) for z in zip(["惊悚", "其他"], [11, 89])],
center=["55%", "70%"],
radius=[60, 80],
label_opts=new_label_opts(),
)
.set_global_opts(
title_opts=opts.TitleOpts(title="Pie-多饼图基本示例"),
legend_opts=opts.LegendOpts(
type_="scroll", pos_top="20%", pos_left="80%", orient="vertical"
),
)
.render("mutiple_pie.html")
)
pyecharts 效果
订制饼图-南丁格尔玫瑰图
import pyecharts.options as opts
from pyecharts.charts import Pie
x_data = ["直接访问", "邮件营销", "联盟广告", "视频广告", "搜索引擎"] # 标签数据
y_data = [335, 310, 274, 235, 400] # 比例数据
data_pair = [list(z) for z in zip(x_data, y_data)] # 组合并推导为列表
data_pair.sort(key=lambda x: x[1])
(
Pie(init_opts=opts.InitOpts(width="1600px", height="800px", bg_color="#2c343c"))
.add(
series_name="访问来源",
data_pair=data_pair, # 数据
rosetype="radius", # 类型
radius="55%",
center=["50%", "50%"],
label_opts=opts.LabelOpts(is_show=False, position="center"),
)
.set_global_opts(
title_opts=opts.TitleOpts(
title="Customized Pie",
pos_left="center",
pos_top="20",
title_textstyle_opts=opts.TextStyleOpts(color="#fff"),
),
legend_opts=opts.LegendOpts(is_show=False),
)
.set_series_opts(
tooltip_opts=opts.TooltipOpts(
trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)"
),
label_opts=opts.LabelOpts(color="rgba(255, 255, 255, 0.3)"),
)
.render("customized_pie.html")
)

Pie - Pie_rosetype
pyecharts 代码
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.faker import Faker
v = Faker.choose()
c = (
Pie()
.add(
"",
[list(z) for z in zip(v, Faker.values())],
radius=["30%", "75%"],
center=["25%", "50%"],
rosetype="radius",
label_opts=opts.LabelOpts(is_show=False),
)
.add(
"",
[list(z) for z in zip(v, Faker.values())],
radius=["30%", "75%"],
center=["75%", "50%"],
rosetype="area",
)
.set_global_opts(title_opts=opts.TitleOpts(title="Pie-玫瑰图示例"))
.render("pie_rosetype.html")
)
pyecharts 效果


