我正在尝试使图例中的标签左对齐,值右对齐。在下面的代码中,我尝试使用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()
您的实现有两个问题。首先,您的饼图标签的长度远远超过您为其分配的字符数.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'})
结果排列很好,但是等宽字体的缺点是有些难看:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句