如何在不使用代理艺术家的情况下向Matplotlib饼图添加图例?

2024-04-16 16:28:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过加入一个图例来缩小我用matplotlib制作的饼图的大小。我认为最大的两个问题是我有18个饼楔,并且使用一个示例代码,我将一个颜色映射合并到一个我不太理解的时髦的numpy数组中。在

我已经做了一些挖掘,我认为我可以合并一个传奇仍然没有使用代理艺术家(我得到了我的代码错误-“传奇不支持)…实例。可改用代理艺术家“)

我使用了这些解决方案的版本-How to add a legend to matplotlib pie chart?理想情况下,我希望我的图例与此处显示的图例相似,只是为楔子添加了更多的标签。我希望在图表的左下角有一个图例,这样我可以减小它的大小并关闭图表周围的标签。在

我还尝试在pie_wedge_collection中添加逗号,正如这里建议的那样-Matplotlib Legends not working 但那也没用。。。在

任何帮助都将不胜感激。谢谢。在

import matplotlib.pyplot as plt
# the pie slices are these percentages:
type_list = [1.37, 3.88, 23.72, 1.11, 0.08, 0.13, 6.74, 20.55, 5.2,\
18.46, 0.48, 6.68, 11.6]
slices = type_list
slices = sorted(slices)

len_slice = int(len(slices)/2)
large = slices[:len_slice]
small = slices[len_slice:]

reordered = large[::2] + small[::2] + large[1::2] + small[1::2]

cmap = plt.cm.prism
colors = cmap(np.linspace(0., 1., len(slices)))

labels = 'Civil Rights', 'Criminal Allegation', 'Departmental Violation', 'Domestic', 'Drugs',\
'Falsification', 'Harassment', 'Lack of Service','Non-Investigatory Incident', 'Physical Abuse',\
'Sexual Crime/Misconduct', 'Unprofessional Conduct', 'Verbal Abuse'

fig = plt.figure(figsize=[14,14.76])
ax = fig.add_subplot(111)

angle = 164.5 + float(sum(small[::2])) / sum(reordered) * 360

pie_wedge_collection = ax.pie(reordered, colors=colors, labels=labels, shadow=True, labeldistance=1.05, startangle=angle);

for pie_wedge in pie_wedge_collection[0]:
    pie_wedge.set_edgecolor('white')

ax.set_title("Complaints Against Philadelphia Police \n (2013 - Present) \n Source:OpenDataPhilly.com");

# user warning comes here (with no legend)...  
plt.legend(pie_wedge_collection, labels, loc="best")
plt.axis('equal')
plt.tight_layout()
plt.show()

Here's a link to the resulting pie chart thus far.


Tags: tolabelslenmatplotlibslicepltcollectionsmall