2013-10-10 98 views
2

我试图让图例中的标签左对齐并且值右对齐。在下面的代码中,我尝试过格式化方法,但是这些值没有正确对齐。matplotlib中的图例对齐

任何暗示/建议,非常感谢。

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() 

回答

3

您的实施有两个问题。首先,你的圆形切片标签比.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这样的字符更多的空间。这是通过使用固定宽度的字体来解决的。

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

结果排队很好,但等宽字体有稍微难看一些下行::在matplotlib,这是通过 enter image description here

+0

谢谢,这确实神奇。我确实为标签指定了更大的宽度,但最终粘贴了旧版本的代码。设置'等宽'属性做了这项工作。再次感谢@drs。 – neon