首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何定位和对齐matplotlib图形图例?

如何定位和对齐matplotlib图形图例?
EN

Stack Overflow用户
提问于 2012-12-16 01:11:38
回答 1查看 54.5K关注 0票数 25

我有一个图,有2行1列的两个子图。我可以添加一个漂亮的图形图例

fig.legend((l1, l2), ['2011', '2012'], loc="lower center", 
           ncol=2, fancybox=True, shadow=True, prop={'size':'small'})

但是,此图例位于图形的中心,而不是我所希望的的中心下方。现在,我可以使用以下命令获得我的坐标轴

axbox = ax[1].get_position()

从理论上讲,我应该能够通过使用元组指定loc关键字来定位图例:

fig.legend(..., loc=(axbox.x0+0.5*axbox.width, axbox.y0-0.08), ...)

这是可行的,除了图例是左对齐的,以便指定图例框的左边缘/角,而不是中心。我搜索了align、horizontalalignment等关键字,但什么也没找到。我也试图获得"legend position",但是legend没有*get_position()*方法。我读过有关*bbox_to_anchor*的文章,但当应用于图形图例时,我无法理解它。这似乎是为斧头传说制作的。

或者:我应该使用移动轴图例吗?但是,为什么首先会有人物传说呢?而且以某种方式“居中对齐”图形图例是可能的,因为loc=“居中下方”也是这样做的。

谢谢你的帮助

马丁

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-20 07:06:47

在这种情况下,您可以使用图形legend方法的轴。无论哪种情况,bbox_to_anchor都是关键。正如您已经注意到的,bbox_to_anchor指定了一个坐标元组(或框)来放置图例。当您使用bbox_to_anchor时,可以将location kwarg视为控制水平和垂直对齐。

区别只在于坐标元组是解释为轴还是图形坐标。

作为使用地物图例的示例:

import numpy as np
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)

x = np.linspace(0, np.pi, 100)

line1, = ax1.plot(x, np.cos(3*x), color='red')
line2, = ax2.plot(x, np.sin(4*x), color='green')

# The key to the position is bbox_to_anchor: Place it at x=0.5, y=0.5
# in figure coordinates.
# "center" is basically saying center horizontal alignment and 
# center vertical alignment in this case
fig.legend([line1, line2], ['yep', 'nope'], bbox_to_anchor=[0.5, 0.5], 
           loc='center', ncol=2)

plt.show()

作为使用axes方法的示例,尝试如下所示:

import numpy as np
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)

x = np.linspace(0, np.pi, 100)

line1, = ax1.plot(x, np.cos(3*x), color='red')
line2, = ax2.plot(x, np.sin(4*x), color='green')

# The key to the position is bbox_to_anchor: Place it at x=0.5, y=0
# in axes coordinates.
# "upper center" is basically saying center horizontal alignment and 
# top vertical alignment in this case
ax1.legend([line1, line2], ['yep', 'nope'], bbox_to_anchor=[0.5, 0], 
           loc='upper center', ncol=2, borderaxespad=0.25)

plt.show()

票数 34
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13894345

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档