问题
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()
回答1:
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:
来源:https://stackoverflow.com/questions/19307884/legend-alignment-in-matplotlib