Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...