当使用 bbox_to_anchor
将图例放置在轴之外时,如 this 所示答案是,当调整图形大小时,轴和图例之间的空间会发生变化。对于静态导出的图来说这很好;您可以简单地调整数字,直到得到正确的结果。但对于您可能想要调整大小的交互式绘图,这是一个问题。从这个例子中可以看出:
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()
结果:
即使调整图形大小,如何确保图例与轴保持相同的距离?
最佳答案
图例与边界框边缘的距离由 borderaxespad
参数设置。 borderaxespad 以字体大小的倍数为单位 - 使其自动独立于轴大小。
所以在这种情况下,
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()
<小时/>
关于在轴下方以恒定距离显示标题的类似问题在 Place title at the bottom of the figure of an axes? 中提出。
关于python - 即使调整图形大小,如何获得图例和轴之间的恒定距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55206575/