Python 如何避免标签重叠&;matplotlib饼图中的自动CT?

Python 如何避免标签重叠&;matplotlib饼图中的自动CT?,python,numpy,matplotlib,plot,pie-chart,Python,Numpy,Matplotlib,Plot,Pie Chart,我的Python代码是: values = [234, 64, 54,10, 0, 1, 0, 9, 2, 1, 7, 7] months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct', 'Nov','Dec'] colors = ['yellowgreen', 'red', 'gold', 'lightskyblue', 'white','lightcoral

我的Python代码是:

values = [234, 64, 54,10, 0, 1, 0, 9, 2, 1, 7, 7]
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
          'Jul','Aug','Sep','Oct', 'Nov','Dec']

colors = ['yellowgreen', 'red', 'gold', 'lightskyblue', 
          'white','lightcoral','blue','pink', 'darkgreen', 
          'yellow','grey','violet','magenta','cyan']

plt.pie(values, labels=labels, autopct='%1.1f%%', shadow=True, 
        colors=colors, startangle=90, radius=1.2)

plt.show()
是否可以显示标签“一月”、“二月”、“三月”等以及百分比,或者:

  • 没有重叠,或
  • 使用
    箭头标记

或者,您可以将图例放在饼图旁边:

import matplotlib.pyplot as plt
import numpy as np

x = np.char.array(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct', 'Nov','Dec'])
y = np.array([234, 64, 54,10, 0, 1, 0, 9, 2, 1, 7, 7])
colors = ['yellowgreen','red','gold','lightskyblue','white','lightcoral','blue','pink', 'darkgreen','yellow','grey','violet','magenta','cyan']
porcent = 100.*y/y.sum()

patches, texts = plt.pie(y, colors=colors, startangle=90, radius=1.2)
labels = ['{0} - {1:1.2f} %'.format(i,j) for i,j in zip(x, porcent)]

sort_legend = True
if sort_legend:
    patches, labels, dummy =  zip(*sorted(zip(patches, labels, y),
                                          key=lambda x: x[2],
                                          reverse=True))

plt.legend(patches, labels, loc='left center', bbox_to_anchor=(-0.1, 1.),
           fontsize=8)

plt.savefig('piechart.png', bbox_inches='tight')


编辑:如您在评论中所述,如果您想保持图例的原始顺序,可以在上述代码中设置
sort\u legend=False
,给出:

试试看布局

plt.tight_layout()

在代码的末尾。这可能会稍微防止重叠。

Hi@Saullo Castro,这是我想要的,但还有一个问题我想要按数组顺序排列的图例。。i、 e,1月,2月,3月,4月,5月,6月..10月,11月,12月。图中按数据(y值)顺序绘制。通过这个答案,我在Python中学习了很多新函数。10/10.精彩的演示!10/10当然!5年后,这仍然解决了我的问题。看起来很棒!我的情况并非如此