Matplotlib中的图例对齐

6
我想将标签左对齐,将值右对齐显示在图例中。在下面的代码中,我尝试使用format方法,但是值没有正确对齐。 非常感谢您提供任何提示/建议。
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个回答

11

你的实现存在两个问题。首先,你的饼图标签比你用.format()分配给它们的字符数要多得多(最长的是16个字符,而你只允许了最多10个字符的空间)。为解决此问题,请将legend行更改为:

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

然而,这只能稍微改善一下。这是因为Matplotlib默认使用的是变宽字体,意味着像m这样的字符会比像i这样的字符占用更多的空间。这可以通过使用等宽字体来解决。在Matplotlib中,可以通过以下方式实现:

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

结果排列得很整齐,但等宽字体的缺点是在某些情况下略微难看:

enter image description here

谢谢,那真是太神奇了。我确实指定了更大的标签宽度,但最终却粘贴了我的旧代码版本。设置“等宽字体”属性就解决了问题。再次感谢@drs。 - neon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接