我知道 bbox_to_anchor 关键字和这个线程,它非常有用地建议如何手动放置图例:
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)
我认为让我感到困惑的是图例实际上并不是从 0.82 开始的,实际上对于我更大的图(有 5 个这种类型的子图),我需要使用图例坐标 bbox_to_anchor=(0.04, 1.15, 1., .102) 以使图例出现在坐标 (0.02, 0.83) 上。但也许我还有其他问题?
最佳答案
loc
参数指定图例放置在边界框的哪个角。 loc
的默认值是 loc="best"
,当使用 bbox_to_anchor
参数时,它会产生不可预知的结果。
因此,在指定 bbox_to_anchor
时,always 也要指定 loc
。
bbox_to_anchor
的默认值为 (0,0,1,1)
,它是整个轴上的边界框。如果指定了不同的边界框,通常使用前两个值就足够了,它们给出了边界框的 (x0, y0)。
下面是一个示例,其中边界框设置为位置 (0.6,0.5)
(绿点)并测试了不同的 loc
参数。因为图例超出边界框,loc
参数可以解释为“图例的哪个角应放置在 2 元组 bbox_to_anchor 参数给定的位置”。
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()
参见 this answer详细解释和问题What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib? .
如果要在坐标轴坐标以外的其他坐标中指定图例位置,可以使用
bbox_transform
参数来实现。如果使用图形坐标可能有意义
ax.legend(bbox_to_anchor=(1,0), loc="lower right", bbox_transform=fig.transFigure)
使用数据坐标可能没有太大意义,但既然您要求它,这将通过 bbox_transform=ax.transData
完成。
关于python - 如何在图坐标中指定matplotlib中的图例位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44413020/