<p><code>loc</code>参数指定图例放置在边界框的哪个角。<code>loc</code>的默认值为<code>loc="best"</code>,当使用<code>bbox_to_anchor</code>参数时,会产生不可预测的结果。<br/>
因此,在指定<code>bbox_to_anchor</code>时,<strong>始终</strong>也指定<code>loc</code></p>
<p><code>bbox_to_anchor</code>的默认值为<code>(0,0,1,1)</code>,它是整个轴上的边界框。如果指定了不同的边界框,则通常足以使用前两个值,这两个值给出了边界框的(x0,y0)</p>
<p>下面是一个示例,其中边界框设置为位置<code>(0.6,0.5)</code>(绿点),并测试不同的<code>loc</code>参数。由于图例扩展到边界框之外,因此<code>loc</code>参数可能被解释为“图例的哪个角应放置在2元组bbox_to_锚定参数给定的位置”</p>
<p><a href="https://i.stack.imgur.com/tpx3W.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tpx3W.png" alt="enter image description here"/></a></p>
<pre><code>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()
</code></pre>
<p>关于详细的解释和问题{a3},特别见{a2}</p>
<p/><hr/>
如果要在轴坐标以外的其他坐标中指定图例位置,可以使用<code>bbox_transform</code>参数。如果可能的话,可以使用图形坐标
<pre><code>ax.legend(bbox_to_anchor=(1,0), loc="lower right", bbox_transform=fig.transFigure)
</code></pre>
<p>使用数据坐标可能没有太大意义,但由于您要求使用数据坐标,因此这将通过<code>bbox_transform=ax.transData</code>完成</p>