原文地址:https://matplotlib.org/gallery/pie_and_polar_charts/pie_features.html#sphx-glr-gallery-pie-and-polar-charts-pie-features-py

基础饼图的演示加了一些额外新特性.

除了基础饼图,这个演示展示了一些可选的特性:

  • slice labels 分类切片
  • auto-labeling the percentage 自动百分比标签
  • offsetting a slice with “explode” 用解剖抵消切片
  • drop-shadow 移除阴影
  • custom start angle 自定义开始角度

关于自定义开始角度提示:

默认的 startangle 是 0, 将在正 x-axis 开始 “Frogs” 切片 . 这个示例设置 startangle = 90 比如所有物体逆时针旋转90度, frog 切片从正 y-axis(y轴) 开始.

import matplotlib.pyplot as plt

# 饼图, 切片将按逆时针方向排列并绘制:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)  # 只有 "explode" 的第二个切片 (i.e. 'Hogs')

fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1.axis('equal')  # 等长径比确保饼图被画成圆形.

plt.show()
代码结果

matplotlib.pyplot.pie

matplotlib.pyplot.pie(xexplode=Nonelabels=Nonecolors=Noneautopct=Nonepctdistance=0.6shadow=Falselabeldistance=1.1startangle=Noneradius=Nonecounterclock=Truewedgeprops=Nonetextprops=Nonecenter=(00)frame=Falserotatelabels=False*data=None)[source]

绘制一个饼图.

制作一个数组x的饼图. 每个楔块的分数面积由 x/sum(x) 给出. 如果 sum(x) < 1, x的值直接给出分数区域,数组不会被标准化 . 饼的结果将有一个大小为 1 - sum(x) 的空的楔子 .

楔形是逆时针绘制的 , 默认从 x-axis(x轴)开始.

Parameters:x : array-like类数组
楔形wedge的大小.
explode : array-like类数组, 可选, 默认: None
如果非 None, 是一个 len(x) 数组 它指定了用来偏移每个楔子的半径的比例.
labels : list列表, 可选, 默认: None
为每个楔子提供标签的字符串序列
colors : array-like, optional, default: None
一组matplotlib颜色参数序列,饼图通过这些参数循环. 如果是None, 将使用当前活动周期中的颜色.
autopct : None (默认), string, or function, 可选
如果非 None, 是否使用字符串或函数将楔形标记为数值 . 标签将被放置在楔内 . 如果是一个格式字符串, 标签label将 fmt%pct. 如果是一个函数function,它将会被调用.
pctdistance : float, 可选, 默认: 0.6
每个饼图切片的中心与autopct生成的文本的开始之间的比值 . 如果 autopct 为None则忽略.
shadow : bool, 可选, 默认: False
在饼下画一个阴影.
labeldistance : float or None, 可选, 默认: 1.1
绘制饼形标签的径向距离 .如果设置为 None, 不会绘制标签label, 而是存储在 legend()
startangle : float, 可选, 默认: None
如果非None, 从x轴逆时针旋转饼图的起始角度 .
radius : float, 可选, 默认: None
饼的半径, 如果 radius 为None  它将被设置为 1.
counterclock : bool, 可选, 默认: True
指定fractions direction片方向,顺时针方向或逆时针方向.
wedgeprops : dict字典, 可选, 默认: None
将参数Dict传递给wedge(楔)对象制作饼. 比如, 你可以传入 wedgeprops = {'linewidth': 3} 将楔形边框线的宽度设置为3 . 更多详情 ,查看 doc/arguments of the wedge object.默认clip_on=False.
textprops : dict字典, 可选, 默认: None
要传给text objects的字典参数.
center : list of float, 可选, 默认: (0, 0)
图表的中心位置 . 取值(0,0)或为2个标量的序列 .
frame : bool, 可选, 默认: False
如果为True,用图表绘制坐标轴框架 .
rotatelabels : bool, 可选, 默认: False
如果为True,将每个标签旋转到对应切片的角度 .
Returns:patches : list
一个 matplotlib.patches.Wedge  序列实例
texts : list
一个label标签 matplotlib.text.Text 列表实例.
autotexts : list
数字标签的 Text  实例列表. 它只有在参数 autopct 不为 None时返回.

注意

如果图形和坐标轴是方形的,饼图可能看起来最好 , 或者 Axes 轴心方向相等. 该方法将轴的长径比设置为“相等”. axes(轴心) 方向比率可以由 Axes.set_aspect 控制.

注意

除了上述参数 , 这个函数可以接受 data 关键字参数. 如果给出这样一个 data  参数 , 下面的参数被替换为  data[<arg>]:

  • 所有参数都具有以下名称 : ‘colors’, ‘explode’, ‘labels’, ‘x’.

作为 data 传递的对象必须支持项访问( data [<arg>])和成员测试( data 中的<arg>)。

给饼和环状线圈(甜甜圈)贴标签 Labeling a pie and a donut

欢迎来到matplotlib面包店. 我们将通过pie method 创建一个饼和环状线圈(甜甜圈)并展示怎么用图例  legend  和注释 annotations 来标记它们 . 与往常一样,我们将从定义导入开始,并创建一个带有子图 subplots 的图. 现在是绘制饼图的时间. 从饼pie的制作开始, 我们从中创建数据和标签列表 .

我们可以提供一个函数给 autopct 参数, 它会通过显示绝对值来扩展自动百分比标记 ; 我们根据相关数据和已知的所有值的和来计算后者.

然后创建pie并存储返回的对象,以备以后使用 . 返回的元组的第一个返回元素是楔形 wedges 列表. 那些可以直接用作图例的句柄 matplotlib.patches.Wedge 补丁. 我们可以使用图例的 bbox_to_anchor  参数将图例放置在饼的外边。 这里我们用坐标轴坐标  (1, 0, 0.5, 1)  连同地点  "center left"; i.e. 图例的左中心点将位于边界框的左中心点 , 从 (1,0) 到 (1.5,1) 在轴坐标系 .

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))

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)

wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
                                  textprops=dict(color="w"))
ax.legend(wedges, ingredients,
          title="Ingredients",
          loc="center left",
          bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=8, weight="bold")

ax.set_title("Matplotlib bakery: A pie")

plt.show()
../../_images/sphx_glr_pie_and_donut_labels_001.png

现在是绘制donut(甜甜圈)的时间. 从甜甜圈食谱开始 , 我们把数据转录成数字 (转换1 egg 为 50 g), 直接画出饼图. 饼图? 等等… 是甜甜圈,对吧? 好吧, 正如我们在这里看到的 , 天天圈就是一个饼, 楔有一定的宽度  width  ,这与它的半径不同. 这很简单 . 这是通过 wedgeprops 参数完成的.

然后我们要通过 annotations 标记楔形 . 我们首先创建一些公共属性的字典,稍后可以将其作为关键字参数传递 . 然后我们遍历所有的楔子和每个楔子。

  • 计算楔形中心的角度 calculate the angle of the wedge’s center,
  • 由此得到该点在圆周上该角处的坐标 from that obtain the coordinates of the point at that angle on the circumference,
  • 确定文本的水平对齐,取决于该点位于圆的哪一侧, determine the horizontal alignment of the text, depending on which side of the circle the point lies,
  • 用获得的角度更新连接样式,使注释箭头从甜甜圈向外 update the connection style with the obtained angle to have the annotation arrow point outwards from the donut,
  • 最后,使用前面确定的所有参数创建注释。 finally, create the annotation with all the previously determined parameters.
fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))

recipe = ["225 g flour",
          "90 g sugar",
          "1 egg",
          "60 g butter",
          "100 ml milk",
          "1/2 package of yeast"]

data = [225, 90, 50, 60, 100, 5]

wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=-40)

bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(arrowprops=dict(arrowstyle="-"),
          bbox=bbox_props, zorder=0, va="center")

for i, p in enumerate(wedges):
    ang = (p.theta2 - p.theta1)/2. + p.theta1
    y = np.sin(np.deg2rad(ang))
    x = np.cos(np.deg2rad(ang))
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = "angle,angleA=0,angleB={}".format(ang)
    kw["arrowprops"].update({"connectionstyle": connectionstyle})
    ax.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
                horizontalalignment=horizontalalignment, **kw)

ax.set_title("Matplotlib bakery: A donut")

plt.show()
../../_images/sphx_glr_pie_and_donut_labels_002.png

这就是甜甜圈donut. 请注意, 如果我们用这个食谱recipe, 材料要大约六个甜甜圈 – 制作一个巨大的甜甜圈是未经测试的,可能会导致厨房(结果)错误。

发表回复