如何使用 tight_layout 保持轴纵横比

How to preserve axis aspect ratio with tight_layout

我有一个包含颜色条和图例的图。我想将图例放在颜色栏右侧的图例之外。为此,我使用 bbox_to_anchor 参数,但这会导致图例被截断:

import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm

_, ax = plt.subplots()

extent = np.r_[0, 1, 0, 1]
space = np.linspace(0, 1)
probs = np.array([[norm.cdf(x + y) for x in space] for y in space])
colormap = ax.imshow(probs, aspect="auto", origin="lower", extent=extent, alpha=0.5)
colorbar = plt.colorbar(colormap, ax=ax)
colorbar.set_label(f"Probability")
ax.scatter(
    [0.2, 0.4, 0.6], [0.8, 0.6, 0.4], color="r", label="Labeled Points",
)
plt.legend(loc="center left", bbox_to_anchor=(1.3, 0.5))
plt.title
plt.show()

图例被截断

为了修复图例,我在 plt.show() 之前插入了对 plt.tight_layout() 的调用,但这会导致纵横比失真:

纵横比扭曲的绘图

如何显示整个图例并保持轴的纵横比?

您可以使用 matplotlib.axes.Axes.set_aspect 来管理轴高度和宽度之间的比率。由于您希望它们相等:

ax.set_aspect(1)

然后您可以使用 matplotlib.pyplot.tight_layout 将图例放入图中。
如果你也想调整边距,你可以使用 matplotlib.pyplot.subplots_adjust.

完整代码

import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm

_, ax = plt.subplots()

extent = np.r_[0, 1, 0, 1]
space = np.linspace(0, 1)
probs = np.array([[norm.cdf(x + y) for x in space] for y in space])
colormap = ax.imshow(probs, aspect="auto", origin="lower", extent=extent, alpha=0.5)
colorbar = plt.colorbar(colormap, ax=ax)
colorbar.set_label(f"Probability")
ax.scatter([0.2, 0.4, 0.6], [0.8, 0.6, 0.4], color="r", label="Labeled Points",)
plt.legend(loc="center left", bbox_to_anchor=(1.3, 0.5))

ax.set_aspect(1)
plt.tight_layout()
plt.subplots_adjust(left = 0.1)

plt.show()