分解为非圆形的Matplotlib饼图

2024-09-28 20:20:12 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:我不能共享实际数据,但这里有一个示例数据框

df = pd.DataFrame({'education_grouped': ['None', 'Primary', 'Secondary', 
'Post-secondary', 'Bachelor', 'Master', 'Doctoral', 'None', 'Primary', 
'Secondary', 'Post-secondary', 'Bachelor', 'Master', 'Doctoral', 'None', 
'Primary', 'Secondary', 'Post-secondary', 'Bachelor', 'Master', 'Doctoral']})

我正在使用以下代码制作一个甜甜圈饼图

sizes = df['education_grouped'].value_counts().sort_index() / df['education_grouped'].value_counts().sum() * 100
educ_order2 = ['None', 'Primary', 'Secondary', 'Post-secondary', 'Bachelor', 'Master', 'Doctoral'] 

cmap = plt.get_cmap("Set2")
colors = cmap(np.array([1, 2, 3, 4, 5, 6, 7]))
explode = (0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05)

fig1, ax1 = plt.subplots()
ax1.pie(sizes,
        labels=educ_order2,
        startangle=90,
        explode=explode,
        colors=colors,
        counterclock=False,
        shadow=False,
        wedgeprops={'edgecolor': 'white'},
        textprops={'fontsize': 7},
        pctdistance=0.8,
        autopct='%1.1f%%')

centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

ax1.axis('equal')
plt.title('Educational attainment', fontsize=16, pad=20)
plt.tight_layout()

然而,我为它不再是一个圆而烦恼。如下所示,一些碎片似乎比其他碎片移动得更远。这对我来说似乎很奇怪,因为我以相同的数量爆炸了所有切片。有人知道这里发生了什么吗

enter image description here


Tags: masternonedfpltpostcmapcolorssecondary
1条回答
网友
1楼 · 发布于 2024-09-28 20:20:12

最好是禁用“爆炸”参数。将其置为零可以消除不平等。相比之下,您可能需要调整radius

sizes = df['education_grouped'].value_counts().sort_index() /    df['education_grouped'].value_counts().sum() * 100
educ_order2 = ['None', 'Primary', 'Secondary', 'Post-secondary', 'Bachelor', 'Master', 'Doctoral'] 

cmap = plt.get_cmap("Set2")
colors = cmap(np.array([1, 2, 3, 4, 5, 6, 7]))

fig1, ax1 = plt.subplots(figsize=(8,12))
ax1.pie(sizes,
    labels=educ_order2,
    radius=1,
    explode=[0, 0, 0, 0, 0, 0, 0],
    startangle=90,
    colors=colors,
    counterclock=False,
    shadow=False,
    wedgeprops={'edgecolor': 'white', 'linewidth': 4},
    textprops={'fontsize': 7},
    pctdistance=0.85,
    autopct='%1.1f%%')

centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

ax1.axis('equal')
plt.title('Educational attainment', fontsize=16, pad=20)
plt.tight_layout()

如果你把其中一个放高一点,比如说explode=[0.2, 0, 0, 0, 0, 0, 0],它会给其中一个派带来很好的特殊效果。该参数可能设计用于突出显示一个或几个分数

相关问题 更多 >