pie 函数用户绘制饼图。绘制饼图的数据由参数 x 提供,每个饼图楔块的分数区域为 x/sum(x) 。如果 sum(x)<1,那么 x 的值直接给出分数区域,数组将不被归一化,生成的饼图将有一个大小为 1-sum(x) 的空楔形。默认情况下,pie 函数从 x 轴开始逆时针绘制饼图楔块。pie 函数的调用格式如下:
pie(x, explode, labels, colors,**kwargs)
pie(x)
绘制一个饼图并加上一些额外的设置。除了基本的饼图之外,还显示了一些可选功能:
完整代码如下:
import matplotlib.pyplot as plt
# step1:准备画图的数据
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0) # 控制第二个饼图楔块弹出,即Hogs弹出
# step2:手动创建一个figure对象,相当于一个空白的画布
figure = plt.figure()
# step3:在画布上添加1个子块,标定绘图位置
axes1 = plt.subplot(1, 1, 1)
# step4:绘制饼图
axes1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
axes1.set_title('Basic pie chart')
# step5:展示
plt.show()
上面代码的运行结果:
完整代码如下:
import matplotlib.pyplot as plt
import numpy as np
# step1:准备画图的数据
recipe = ["375 g flour",
"75 g sugar",
"250 g butter",
"300 g berries"]
data = [float(x.split()[0]) for x in recipe]
ingredients = [x.split()[-1] for x in recipe]
# 自定义一个函数,用于计算每个饼块所占的百分比,并拼接文本
def func(pct, allvals):
# 计算百分比
absolute = int(pct / 100. * np.sum(allvals))
# 按格式拼接饼块展示文本
return "{:.1f}%\n({:d} g)".format(pct, absolute)
# step2:手动创建一个figure对象,相当于一个空白的画布
figure = plt.figure()
# step3:在画布上添加1个子块,标定绘图位置
axes1 = plt.subplot(1, 1, 1)
# step4:绘制饼图,通过参数autopct指定的字符串标记楔块
wedges, texts, autotexts = axes1.pie(data, autopct=lambda pct: func(pct, data),
textprops=dict(color="w"))
# step5:绘制图例
axes1.legend(wedges, ingredients,
title="Ingredients",
loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))
# step6:设置饼图文本格式和标题
plt.setp(autotexts, size=8, weight="bold")
axes1.set_title("Matplotlib bakery: A pie")
# step7:展示
plt.show()
上面代码的运行结果: