【问题标题】:legend alignment in matplotlibmatplotlib 中的图例对齐
【发布时间】:2013-10-18 22:16:56
【问题描述】:

我正在尝试使图例中的标签左对齐和值右对齐。在下面的代码中,我尝试过使用格式方法,但值没有正确对齐。

非常感谢任何提示/建议。

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

【问题讨论】:

    标签: matplotlib legend


    【解决方案1】:

    您的实施存在两个问题。首先,您的饼图标签比您使用 .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'})
    

    结果排列得很好,但是等宽字体的缺点是对某些人来说有点难看:

    【讨论】:

    • 谢谢,这很神奇。我确实为标签指定了更大的宽度,但最终粘贴了我的旧版本代码。设置 'monospace' 属性完成了工作。谢谢,再次@drs。
    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多