matplotlib中的图例对齐 [英] legend alignment in matplotlib

查看:93
本文介绍了matplotlib中的图例对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使图例中的标签左对齐,值右对齐.在下面的代码中,我尝试使用format方法,但是值未正确对齐.

I'm trying to get labels left-aligned and values right-aligned in the legend. In below code, I've tried with format method, but the values are not properly aligned.

任何提示/建议都将不胜感激.

Any hint/suggestions is greatly appreciated.

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 行更改为:

There are two problems with your implementation. First, your pie slice labels are much longer than the number of characters you allocate to them with .format() (the longest is 16 characters and you only allowed space for up to 10 characters). To fix this, change the legend line to:

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

但是,这只会使情况有所改善.这是因为默认情况下,matplotlib使用的是可变宽度字体,这意味着像 m 这样的字符会比像 i 这样的字符占用更多的空间.通过使用固定宽度的字体可以解决此问题.在matplotlib中,这是通过以下方式实现的:

However, this only improves things slightly. This is because matplotlib is using a variable-width font by default, meaning characters like m take up more space than characters like i. This is fixed by using a fixed-width font. In matplotlib, this is achieved by:

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

结果排列很好,但是等宽字体的缺点是有些难看:

The result lines up nicely, but the monospace font has the downside of being slightly ugly to some:

这篇关于matplotlib中的图例对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆