【问题标题】:Matplotlib pie chart with explode not roundMatplotlib 饼图与爆炸不圆
【发布时间】:2020-11-30 13:30:27
【问题描述】:

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

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

但是,我对它不再显示为圆圈的事实感到困扰。见下文,似乎有些部分比其他部分移动得更远。这对我来说似乎很奇怪,因为我将所有切片爆炸了相同的数量。有人知道这里发生了什么吗?

【问题讨论】:

  • 你有作为输入的DataFrame吗?
  • 添加了一个示例数据框。

标签: python matplotlib pie-chart explode donut-chart


【解决方案1】:

最好关闭explode参数。将其设为零可以消除不平等。相比之下,你可能想适应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],它给其中一个馅饼带来了很好的特殊效果。该参数可能旨在突出显示一个或几个分数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    相关资源
    最近更新 更多