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

5
我正在使用matplotlib绘制一些饼图,但有些图表上的百分比标签重叠在一起,看起来很杂乱。有没有办法改变文字位置,使其全部可读?
下面是我得到的一个示例 - 类别“Others”和“ALD2_OH”重叠在一起,无法阅读。
我的绘图代码如下:
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个回答

6
您可能需要将窄楔形物的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))

这会产生以下结果(我在一定程度上模拟了您的数据): 一个图表

1
设计思路:将百分比移至标签下方的第二行? - cphlewis
谢谢Andrey - 这个很有效。还有谢谢cphlewis - 这不是一个坏主意。我想我只是有点懒,让Python自动计算百分比并绘制它们,我可以再加一行代码来自己计算百分比! - doug

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接