Python 如何在图形坐标中指定matplotlib中的图例位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44413020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:59:36  来源:igfitidea点击:

How to specify legend position in matplotlib in graph coordinates

pythonmatplotlib

提问by mzzx

I am aware of the bbox_to_anchor keyword and this thread, which very helpfully suggests how to manually place the legend:

我知道 bbox_to_anchor 关键字和这个线程,它非常有帮助地建议如何手动放置图例:

How to put the legend out of the plot

如何将图例排除在情节之外

However, I'd like to use the coordinates of my x- and y-axis in the graph to specify the legend position (inside the plot), as I might need to move the figure into a large figure with a different axis environment, and I don't want to manually play around with those coordinates every time I do this. Is this possible?

但是,我想使用图中 x 轴和 y 轴的坐标来指定图例位置(在图中),因为我可能需要将图形移动到具有不同轴环境的大图形中,我不想每次这样做时都手动调整这些坐标。这可能吗?

Edit: A small example is here:

编辑:这里有一个小例子:

import numpy as n
f, axarr = plt.subplots(2,sharex=True)
axarr[1].set_ylim([0.611,0.675])
axarr[0].set_ylim([0.792,0.856]) 
axarr[0].plot([0, 0.04, 0.08],n.array([ 0.83333333,  0.82250521,0.81109048]), label='test1') 
axarr[0].errorbar([0, 0.04, 0.08],n.array([ 0.8,  0.83,   0.82]),n.array([0.1,0.1,0.01]), label='test2') 
axarr[1].plot([0, 0.04, 0.08],n.array([ 0.66666667,  0.64888304,  0.63042428]))
axarr[1].errorbar([0, 0.04, 0.08],n.array([ 0.67,  0.64,  0.62]),n.array([ 0.01,  0.05,  0.1]))
axarr[0].legend(bbox_to_anchor=(0.04, 0.82, 1., .102),labelspacing=0.1,       handlelength=0.1, handletextpad=0.1,frameon=False, ncol=4, columnspacing=0.7)

enter image description here

在此处输入图片说明

I think what confuses me is that the legend does not actually start at 0.82, and indeed for my larger plot (with 5 subplots of this type), I need to use legend coordinates bbox_to_anchor=(0.04, 1.15, 1., .102) in order to make the legend appear on coordinates (0.02, 0.83). But maybe I am getting something else wrong?

我认为让我感到困惑的是,图例实际上并不是从 0.82 开始的,实际上对于我较大的图(有 5 个这种类型的子图),我需要使用图例坐标 bbox_to_anchor=(0.04, 1.15, 1., .102)为了使图例出现在坐标 (0.02, 0.83) 上。但也许我还有其他问题?

回答by ImportanceOfBeingErnest

The locparameter specifies in which corner of the bounding box the legend is placed. The default for locis loc="best"which gives unpredictable results when the bbox_to_anchorargument is used.
Therefore, when specifying bbox_to_anchor, alwaysspecify locas well.

loc参数指定图例放置在边界框的哪个角。当使用参数时,默认值locloc="best"给出不可预测的结果bbox_to_anchor
因此,在指定 时bbox_to_anchor,也始终指定loc

The default for bbox_to_anchoris (0,0,1,1), which is a bounding box over the complete axes. If a different bounding box is specified, is is usually sufficient to use the first two values, which give (x0, y0) of the bounding box.

默认的bbox_to_anchor就是(0,0,1,1),这是在整个轴的边框。如果指定了不同的边界框,通常足以使用前两个值,它们给出边界框的 (x0, y0)。

Below is an example where the bounding box is set to position (0.6,0.5)(green dot) and different locparameters are tested. Because the legend extents outside the bounding box, the locparameter may be interpreted as "which corner of the legend shall be placed at position given by the 2-tuple bbox_to_anchor argument".

下面是将边界框设置为位置(0.6,0.5)(绿点)并loc测试不同参数的示例。因为图例范围在边界框之外,该loc参数可以解释为“图例的哪个角应放置在由 2 元组 bbox_to_anchor 参数给出的位置”。

enter image description here

在此处输入图片说明

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6, 3
fig, axes = plt.subplots(ncols=3)
locs = ["upper left", "lower left", "center right"]
for l, ax in zip(locs, axes.flatten()):
    ax.set_title(l)
    ax.plot([1,2,3],[2,3,1], "b-", label="blue")
    ax.plot([1,2,3],[1,2,1], "r-", label="red")
    ax.legend(loc=l, bbox_to_anchor=(0.6,0.5))
    ax.scatter((0.6),(0.5), s=81, c="limegreen", transform=ax.transAxes)

plt.tight_layout()    
plt.show()

See especially this answerfor a detailed explanation and the question What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib?.

请特别参阅此答案以获取详细说明和问题“bbox_to_anchor”的 4 元素元组参数在 matplotlib 中意味着什么?.



如果要在轴坐标以外的其他坐标中指定图例位置,可以使用bbox_transformbbox_transform参数来实现。如果使用图形坐标可能有意义

ax.legend(bbox_to_anchor=(1,0), loc="lower right",  bbox_transform=fig.transFigure)

It may not make too much sense to use data coordinates, but since you asked for it this would be done via bbox_transform=ax.transData.

使用数据坐标可能没有太大意义,但既然你要求它,这将通过bbox_transform=ax.transData.

回答by Draho? Ma?ar

You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

您可以使用 loc 参数更改图例的位置。 https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

import matplotlib.pyplot as plt

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

回答by llin

In addition to @ImportanceOfBeingErnest's post, I use the following line to add a legend at an absolute position in a plot.

除了@ImportanceOfBeingErnest 的帖子之外,我还使用以下行在图中的绝对位置添加图例。

plt.legend(bbox_to_anchor=(1.0,1.0),\
    bbox_transform=plt.gcf().transFigure)

For unknown reasons, bbox_transform=fig.transFiguredoes not work with me.

由于未知原因,bbox_transform=fig.transFigure对我不起作用。

回答by user3140225

According to the matplotlib legend documentation:

根据matplotlib图例文档

The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchorwill be ignored).

位置也可以是一个 2 元组,给出轴坐标中图例左下角的坐标(在这种情况下bbox_to_anchor将被忽略)。

Thus, one could use:

因此,可以使用:

plt.legend(loc=(x, y))

to set the legend's lower left corner to the specified (x, y)position.

将图例的左下角设置到指定(x, y)位置。