即使调整了大小,如何在图例和轴之间获得恒定的距离? [英] How to get constant distance between legend and axes even when the figure is resized?
问题描述
如此答案中所述,使用bbox_to_anchor
将图例放置在轴外时,轴与调整图的大小时,图例会更改.对于静态导出图,这很好.您可以简单地调整数字,直到正确为止.但是对于可能需要调整大小的交互式绘图,这是一个问题.如本例所示:
When placing the legend outside of the axes using bbox_to_anchor
as in this answer, the space between the axes and the legend changes when the figure is resized. For static exported plots this is fine; you can simply tweak the numbers until you get it right. But for interactive plots that you might want to resize, this is a problem. As can be seen in this example:
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(5)
y = np.random.randn(5)
fig, ax = plt.subplots(tight_layout=True)
ax.plot(x, y, label='data1')
ax.plot(x, y-1, label='data2')
legend = ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), ncol=2)
plt.show()
结果:
即使调整了图形的尺寸,如何确保图例与轴之间保持相同的距离?
How can I make sure that the legend keeps the same distance from the axes even when the figure is resized?
推荐答案
图例距边界框边缘的距离由borderaxespad
参数设置. borderaxespad
以fontsize的倍数为单位-使其自动独立于轴大小.
因此,在这种情况下
The distance of a legend from the bounding box edge is set by the borderaxespad
argument. The borderaxespad
is in units of multiples of the fontsize - making it automatically independent of the axes size.
So in this case,
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = np.random.randn(5)
fig, ax = plt.subplots(constrained_layout=True)
ax.plot(x, y, label='data1')
ax.plot(x, y-1, label='data2')
legend = ax.legend(loc="upper center", bbox_to_anchor=(0.5,0), borderaxespad=2)
plt.show()
在 查看全文