0

I'm trying to reduce the size of a pie chart I've made using matplotlib by incorporating a legend. I think the two biggest problems are that I have 18 pie wedges, and using a sample code I incorporated a color map in a funky numpy array I don't quite understand.

I've done some digging and I think I may be able to incorporate a legend still without using proxy artists (I get this error with my code - "Legend does not support)...instances. A proxy artist may be used instead")

I used versions of this solutions to no avail - How to add a legend to matplotlib pie chart? Ideally I would like my legend to be similar to the one shown here, just with many more labels for the wedges. I'd like a legend to the bottom left of my chart so that I could reduce its size and turn off the labels around the chart.

I also tried adding commas to pie_wedge_collection as was suggested here - Matplotlib Legends not working but that also didn't work...

Any help would be much appreciated. Thanks.

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.

champezius
  • 21
  • 4
  • You could use pandas. See [here](https://stackoverflow.com/a/30060628/2454357) or [here](https://stackoverflow.com/a/48589225/2454357) for example. – Thomas Kühn Feb 12 '19 at 07:42

1 Answers1

0

It's the same here as in other answers.

wedges, texts = ax.pie(reordered, colors=colors, labels=labels, shadow=True, labeldistance=1.05)

for pie_wedge in wedges:
    pie_wedge.set_edgecolor('white')

plt.legend(wedges, labels, loc="best")
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712