我正在尝试使图例中的标签左对齐和值右对齐。在下面的代码中,我尝试了 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()
Run Code Online (Sandbox Code Playgroud)
你的实现有两个问题。首先,您的饼图切片标签比您分配给它们的字符数长得多.format()(最长为 16 个字符,您最多只允许 10 个字符的空间)。要解决此问题,请将legend行更改为:
legends = ['{:<16}-{:>8,d}'.format(labels[idx], fracs[idx]) for idx in range(len(labels))]
^-- change this character
Run Code Online (Sandbox Code Playgroud)
然而,这只是稍微改善了一些事情。这是因为 matplotlib 默认使用可变宽度字体,这意味着像m这样的字符比像i这样的字符占用更多的空间。这是通过使用固定宽度字体来解决的。在 matplotlib 中,这是通过以下方式实现的:
pl.legend(legends, loc=1, prop={'family': 'monospace'})
Run Code Online (Sandbox Code Playgroud)
结果排列得很好,但等宽字体的缺点是对某些人来说有点难看:
