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

2024-06-30 16:48:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道bbox_to_锚定关键字和此线程,它非常有助于建议如何手动放置图例:

How to put the legend out of the plot

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

编辑:下面是一个小例子:

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

我想让我困惑的是,图例实际上并不是从0.82开始的,事实上,对于我的更大的图(有5个这种类型的子图),我需要使用图例坐标bbox_to_anchor=(0.04,1.15,1.,.102),以便使图例显示在坐标(0.02,0.83)上。但也许我有什么不对劲?


Tags: theto图形plot手动arraylabelanchor
3条回答

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

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

不知什么原因,bbox_transform=fig.transFigure对我不起作用。

loc参数指定图例放置在边界框的哪个角。loc的默认值是loc="best",在使用bbox_to_anchor参数时会产生不可预测的结果。
因此,在指定bbox_to_anchor时,总是同时指定loc

bbox_to_anchor的默认值是(0,0,1,1),这是整个轴上的边界框。如果指定了不同的边界框,则is通常足以使用前两个值,即边界框的(x0,y0)。

下面是一个示例,其中边界框设置为位置(0.6,0.5)(绿点),并测试不同的loc参数。由于图例在边界框之外,因此loc参数可以解释为“图例的哪个角应放置在2元组bbox_to_锚定参数指定的位置”。

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

有关详细说明和问题What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib?,请特别参阅this answer


如果要在轴坐标以外的其他坐标中指定图例位置,可以使用bbox_transform参数来指定。如果可以使用数字坐标
ax.legend(bbox_to_anchor=(1,0), loc="lower right",  bbox_transform=fig.transFigure)

使用数据坐标可能没有太多意义,但由于您要求使用数据坐标,因此这将通过bbox_transform=ax.transData完成。

可以使用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()

相关问题 更多 >