Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

legend alignment in matplotlib

I'm trying to get labels left-aligned and values right-aligned in the legend. In below code, I've tried with format method, but the values are not properly aligned.

Any hint/suggestions is greatly appreciated.

import matplotlib.pyplot as pl

# make a square figure and axes
pl.figure(1, figsize=(6,6))

labels = 'FrogsWithTail', 'FrogsWithoutTail', 'DogsWithTail', 'DogsWithoutTail'
fracs = [12113,8937,45190, 10]

explode=(0, 0.05, 0, 0)
pl.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
pl.title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

legends = ['{:<10}-{:>8,d}'.format(labels[idx], fracs[idx]) for idx in    range(len(labels))]

pl.legend(legends, loc=1)

pl.show()
like image 919
neon Avatar asked Oct 10 '13 23:10

neon


People also ask

How do I fix the legend position in Matplotlib?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.


1 Answers

There are two problems with your implementation. First, your pie slice labels are much longer than the number of characters you allocate to them with .format() (the longest is 16 characters and you only allowed space for up to 10 characters). To fix this, change the legend line to:

legends = ['{:<16}-{:>8,d}'.format(labels[idx], fracs[idx]) for idx in    range(len(labels))]
                ^-- change this character

However, this only improves things slightly. This is because matplotlib is using a variable-width font by default, meaning characters like m take up more space than characters like i. This is fixed by using a fixed-width font. In matplotlib, this is achieved by:

pl.legend(legends, loc=1, prop={'family': 'monospace'})

The result lines up nicely, but the monospace font has the downside of being slightly ugly to some: enter image description here

like image 87
drs Avatar answered Oct 12 '22 07:10

drs