向嵌套饼图添加图例

Posted

技术标签:

【中文标题】向嵌套饼图添加图例【英文标题】:Add legends to nested pie charts 【发布时间】:2019-08-11 13:46:12 【问题描述】:

我想在嵌套饼图的内部饼图中添加图例:

import matplotlib.pyplot as plt

# Make data: I have 3 groups and 7 subgroups
group_names=['groupA', 'groupB', 'groupC']
group_size=[12,11,30]
subgroup_names=['A.1', 'A.2', 'A.3', 'B.1', 'B.2', 'C.1', 'C.2', 'C.3', 
'C.4', 'C.5']
subgroup_size=[4,3,5,6,5,10,5,5,4,6]

# Create colors
a, b, c=[plt.cm.Blues, plt.cm.Reds, plt.cm.Greens]

# First Ring (outside)
fig, ax = plt.subplots()
ax.axis('equal')
mypie, _ = ax.pie(group_size, radius=1.3, labels=group_names, colors= 
[a(0.6), b(0.6), c(0.6)] )
plt.setp( mypie, width=0.3, edgecolor='white')

# Second Ring (Inside)
mypie2, _ = ax.pie(subgroup_size, radius=1.3-0.3, 
labels=subgroup_names, labeldistance=0.7, colors=[a(0.5), a(0.4), 
a(0.3), b(0.5), b(0.4), c(0.6), c(0.5), c(0.4), c(0.3), c(0.2)])
plt.setp( mypie2, width=0.4, edgecolor='white')
plt.margins(0,0)

subgroup_names_legs=['A.1:a1desc', 'A.2:a2desc', 'A.3:a3desc', 
'B.1:b1desc', 'B.2:b2desc', 'C.1:c1desc', 'C.2:c2desc', 'C.3:c3desc', 
'C.4:c4desc', 'C.5:c5desc']
plt.legend(subgroup_names_legs,loc='best')

# show it
plt.show()

所以我得到了这个结果:

我想在图例中正确引用颜色(例如,A1、A2 和 A3 是不同种类的蓝色等)

另外,如何以不与图表重叠的方式显示图例?

【问题讨论】:

关于图例的放置位置,请参阅Legend overlaps with the pie chart 【参考方案1】:

问题在于,首先使用labels=subgroup_names 分配图例,然后使用plt.legend(subgroup_names_legs,loc='best') 重新分配它们。因此,您正在覆盖现有值并因此破坏订单这就是您看到不匹配颜色的原因。

为避免图例框与图形重叠,可以将其位置指定为loc=(0.9, 0.1)

要摆脱外部饼图的图例,您可以获取图例句柄和标签,然后排除前三个条目,这样您就只有内部饼图的图例了

# First Ring (outside)
fig, ax = plt.subplots()
ax.axis('equal')
mypie, _ = ax.pie(group_size, radius=1.3, labels=group_names, colors= 
[a(0.6), b(0.6), c(0.6)] )
plt.setp( mypie, width=0.3, edgecolor='white')

# Second Ring (Inside)
mypie2, _ = ax.pie(subgroup_size, radius=1.3-0.3, 
labels=subgroup_names, labeldistance=0.7, colors=[a(0.5), a(0.4), 
a(0.3), b(0.5), b(0.4), c(0.6), c(0.5), c(0.4), c(0.3), c(0.2)])
plt.setp( mypie2, width=0.4, edgecolor='white')
plt.margins(0,0)

plt.legend(loc=(0.9, 0.1))
handles, labels = ax.get_legend_handles_labels()

ax.legend(handles[3:], subgroup_names_legs, loc=(0.9, 0.1))
plt.show()

【讨论】:

我明白了,问题是我想要图例,因为子组中写的空间很小,所以我想用图例来描述每个 A1、A2、A3 ...。另一方面,我不想要传说中的A,B,C组,因为在圆圈附近写它们的空间很大。 @Laura:我已经编辑了我的解决方案来回答你的观点。如果不是您需要的,请告诉我。 感谢@Bazingaa!我不需要在传说中复制与内部派相同的内容。我需要在每个子组的图例中添加更多文本。这就是原因,因为我创建了 subgroup_names_legs。例如,在内圈我有“A.1”,但图例应该说“A.1:A.1 的描述”。我决定这样做是因为在情节中写每个子组的描述的空间非常小 非常感谢,非常有用! 再问一个问题@Bazingaa:你知道如何将百分比放在外圈吗?

以上是关于向嵌套饼图添加图例的主要内容,如果未能解决你的问题,请参考以下文章

Highcharts 饼图设置了显示图例 怎样给图例添加点击事件

饼图图例颜色未更新 mpandroidchart

python可视化---饼图添加图例

在 R 中使用 ggplot2 向饼图图例添加值

dc.js饼图图例溢出

使用matplotlib绘制定制化饼图(图例比例标签支持中文等)