编辑:我无法共享实际数据,但这里是一个示例数据框
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 了相同的数量。有人知道这里发生了什么吗?
最佳答案
最好关闭 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/