python - Matplotlib 饼图 explode 而不是圆形

标签 python matplotlib pie-chart explode donut-chart

编辑:我无法共享实际数据,但这里是一个示例数据框

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()

但是,我对它不再显示为圆形这一事实感到困扰。请看下面,似乎有些棋子比其他棋子移得更远。这对我来说似乎很奇怪,因为我将所有切片 explode 了相同的数量。有人知道这里发生了什么吗?

enter image description here

最佳答案

最好关闭 explode 参数。将其设置为零可以消除不平等。相比之下,您可能需要调整半径

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],它给其中一个馅饼带来了很好的特效。该参数可能旨在突出显示一个或几个分数。

关于python - Matplotlib 饼图 explode 而不是圆形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65074529/

相关文章:

python - 在python中对不同的列进行分组

winforms - 关于为饼图创建标签的 F# 说明

javascript - 防止D3饼图中的文本重叠

python - AES 256 加密 -> 更改初始化向量会在不知道 key 的情况下稍微更改解密的消息

python - Pandas GroupBy计算满足一定条件的加权百分比

python - 为什么在 Python 中关闭 Sqlite3 的游标

python - Seaborn:带有频率的计数图()

Python matplotlib 颜色条 : all on last axis

python - 如何在 Matplotlib 中的可自定义位置的颜色栏上设置枢轴?

javascript - float 饼图标签