更改matplotlib饼图上的autopct标签位置

时间:2015-03-20 12:27:57

标签: python matplotlib label pie-chart

我正在matplotlib中绘制一些饼图,并且我的某些图表上的百分比标签相互重叠并且看起来很混乱。有没有办法改变文本的位置,所以它是可读的? 我得到的例子如下:“其他”和“ALD2_OH”类别重叠且不可读。 enter image description here

我的绘图代码在这里:

matplotlib.rcParams.update({'font.size': 18})
plt.figure(figsize=(11,11))

labels = ['ALD2 + OH','PAN + $therm$','ALD2 + NO$_3$','ATOOH + $hv$',
          'Others',]

colours = ['BlueViolet','DarkMagenta','DarkOrchid','DarkViolet','Purple'
           ]

patches, texts,autotexts = plt.pie(main_producers, labels=labels, colors = colours,
        autopct='%1.1f%%', startangle = 90)

plt.title('Contribution to MCO$_3$ yeild')

希望有人可以提供帮助!

由于

1 个答案:

答案 0 :(得分:2)

您可能希望沿着半径从楔形中心移动autotexts个窄楔形:

for patch, txt in zip(patches, autotexts):
    # 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.7 * 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))

这会产生(我在某种程度上模拟了你的数据): a diagram