以不相互接触的方式定位标签 甜甜圈图 matplotlib 熊猫



中间甜甜圈的标签相互接触。 如何确保标签位于它们所属部分的中间但不相互接触?

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

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

你可以尝试这样的事情:

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

最新更新