嵌套饼图#

以下示例展示了在 Matplotlib 中构建嵌套饼图的两种方法。这种图表通常被称为甜甜圈图。

另请参阅 左心室靶心图 示例。

import matplotlib.pyplot as plt
import numpy as np

构建饼图最直接的方法是使用 pie 方法。

在这种情况下,饼图的值对应于组中的计数。我们首先生成一些假数据,对应于三个组。在内圈中,我们将每个数字视为属于其自己的组。在外圈中,我们将它们绘制为其原始三个组的成员。

通过 wedgeprops 参数为饼图的楔形设置 width,可以实现甜甜圈形状的效果。

fig, ax = plt.subplots()

size = 0.3
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])

cmap = plt.colormaps["tab20c"]
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap([1, 2, 5, 6, 9, 10])

ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
       wedgeprops=dict(width=size, edgecolor='w'))

ax.pie(vals.flatten(), radius=1-size, colors=inner_colors,
       wedgeprops=dict(width=size, edgecolor='w'))

ax.set(aspect="equal", title='Pie plot with `ax.pie`')
plt.show()
Pie plot with `ax.pie`

然而,你可以通过在极坐标系下的Axes上使用条形图来实现相同的输出。这可能会在图表的具体设计上提供更多的灵活性。

在这种情况下,我们需要将条形图的 x 值映射到圆的弧度上。值的累积和用作条形的边缘。

fig, ax = plt.subplots(subplot_kw=dict(projection="polar"))

size = 0.3
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])
# Normalize vals to 2 pi
valsnorm = vals/np.sum(vals)*2*np.pi
# Obtain the ordinates of the bar edges
valsleft = np.cumsum(np.append(0, valsnorm.flatten()[:-1])).reshape(vals.shape)

cmap = plt.colormaps["tab20c"]
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap([1, 2, 5, 6, 9, 10])

ax.bar(x=valsleft[:, 0],
       width=valsnorm.sum(axis=1), bottom=1-size, height=size,
       color=outer_colors, edgecolor='w', linewidth=1, align="edge")

ax.bar(x=valsleft.flatten(),
       width=valsnorm.flatten(), bottom=1-2*size, height=size,
       color=inner_colors, edgecolor='w', linewidth=1, align="edge")

ax.set(title="Pie plot with `ax.bar` and polar coordinates")
ax.set_axis_off()
plt.show()
Pie plot with `ax.bar` and polar coordinates

由 Sphinx-Gallery 生成的图库