以不互相接触的方式放置标签donutplot matplotlib pandas

时间:2018-08-15 09:54:11

标签: python pandas matplotlib pie-chart

中间甜甜圈的标签相互接触。 如何确保标签位于标签所属部分的中间,但又不会彼此碰触?

使图形变大无济于事,更改标签距离不会更改标签之间的距离,而是会改变图形中的位置。

df1   = pd.DataFrame({'group1': ['bar', 'bar', 'baz', 'baz', 'baz', 'baz'], 
                  'group2': ['one cs', 'two s', 'one cs', 'two seds', 'three fe', 'four cs'],
                  'count': [15,19,14,1,2,1]})
outside = df1.groupby('group1')['count'].sum()
middle =  df1.groupby(['group1','group2'])['count'].sum()

plt.pie(outside, startangle=90, labels=outside.index,textprops=dict(color="black"), pctdistance=0.90 )

plt.pie(middle, labeldistance=0.75, radius=0.75, labels=middle.reset_index().iloc[:,1], startangle=90,   textprops=dict(color="black") )

centre_circle = plt.Circle((0,0),0.5,color='black', fc='white',linewidth=0)
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

plt.axis('equal')
plt.tight_layout() 
plt.show()

1 个答案:

答案 0 :(得分:0)

您可以尝试类似this的内容:

patches, texts = plt.pie(middle, labeldistance=0.75, radius=0.75, labels=middle.reset_index().iloc[:,1], startangle=90,   textprops=dict(color="black") )

并在plt.show()

之前添加此部分
for patch, txt in zip(patches, texts):
    # the angle at which the text is located
    ang = (patch.theta2 + patch.theta1) / 2.
    # new coordinates of the text, 0.7 is the distance from the center
    x = patch.r * 0.7 * np.cos(ang*np.pi/180)
    y = patch.r * 0.8 * np.sin(ang*np.pi/180)
    # if patch is narrow enough, move text to new coordinates
    if (patch.theta2 - patch.theta1) < 10.:
        txt.set_position((x, y))