Nate
Nate

Reputation: 61

Legend on pie chart matplotlib

I am trying to make the box for my legend smaller and placed in the upper left hand corner of my pie chart. So far I have: pumsData = pd.DataFrame.from_csv('ss13hil.csv')

pieLabels = ['English Only','Spanish','Other Indo-European','Asian and Pacific Island Languages','Other']  
plt.pie(pumsData.HHL.value_counts())  
plt.axis('equal')  
plt.title('Household Languages')  
plt.legend(pieLabels,loc=2,borderpad=0.05)  

the output for my chart is:
https://i.sstatic.net/WbO4U.png

enter image description here

but I would like it to look like this:

https://i.sstatic.net/cBxLz.png

enter image description here

enter code here

Upvotes: 1

Views: 4572

Answers (1)

superdex75
superdex75

Reputation: 86

If you explicitly create an axes instance as object instead of just using functions from the pyplot module, you can easier access plot properties. with bbox_to_anchor=(0.5,0.90) as argument in ax.legend() you can shift the legend in the figure. Try this code:

import matplotlib.pyplot as plt

pieLabels = ['English Only',
             'Spanish',
             'Other Indo-European',
             'Asian and Pacific Island Languages',
             'Other']  

fig, ax  = plt.subplots(1,1,figsize=(4,4))

ax.pie([1,2,3,4,5], labels=pieLabels, labeldistance=9999999)
ax.set(adjustable='box-forced', aspect='equal')
ax.set_title('Household Languages')

handles, labels = ax.axes.get_legend_handles_labels()
ax.legend(handles, labels, prop={'size':6},
          bbox_to_anchor=(0.5,0.90),
          bbox_transform=fig.transFigure)

plt.show()

It should produce this figure: enter image description here

Upvotes: 2

Related Questions