首页 > 解决方案 > 如何在matplotlib的嵌套饼图中将值放在外部饼图中

问题描述

数据:

import numpy as np
import matplotlib.pyplot as plt

labels=['Cat','Dog','Human','Rabbit']
data1=[35,80,2,20]
data2=[5,3,80,8]

我正在使用上述数据绘制嵌套饼图:

size=0.3
fig,ax=plt.subplots(figsize=(20,10))
cmap=plt.get_cmap('tab20c')
outer_colors=cmap(np.arange(0,3)*5)
inner_colors=cmap(np.arange(0,3)*5)
ax.pie(x=data1,autopct='%.2f%%',shadow=True,startangle=180,radius=1,wedgeprops={'width':size,'edgecolor':'c'},colors=outer_colors)
ax.pie(x=data2,autopct='%.2f%%',shadow=True,startangle=180,radius=0.5,wedgeprops={'width':size,'edgecolor':'c'},colors=inner_colors)
plt.title('Good vs Bad Pets',fontsize=18,weight='bold')
plt.legend(labels,fontsize=15)
plt.show()

上述代码的输出:

在此处输入图像描述

我的问题是:

从上图中我们可以看到,在内部饼图中,值(%)也在图中,但它不在外部图中。

那么我该怎么做呢?

预期输出:

在此处输入图像描述

标签: pythonmatplotlibdata-visualization

解决方案


您要查找的参数是pctdistance. 如pie 文档所述,默认值为0.6. size=0.3因为您有一个和的外环radius=1,所以这会导致标签被放置在内部区域中。此处的示例通过指定将标签居中在外环的中心pctdistance

size=0.3
fig, ax = plt.subplots(figsize=(20,10))
cmap = plt.get_cmap('tab20c')
outer_colors = cmap(np.arange(0,3)*5)
inner_colors = cmap(np.arange(0,3)*5)
wedges, text, autopct=ax.pie(x=data1, autopct='%.2f%%', shadow=True,
                             startangle=180, radius=1,
                             wedgeprops={'width':size, 'edgecolor':'c'},
                             colors=outer_colors, pctdistance=(1-size/2))
ax.pie(x=data2, autopct='%.2f%%', shadow=True, startangle=180, radius=0.5,
       wedgeprops={'width':size, 'edgecolor':'c'}, colors=inner_colors)
plt.title('Good vs Bad Pets',fontsize=18,weight='bold')
plt.legend(labels,fontsize=15)
plt.show()

外圈带有标签的馅饼


推荐阅读