如何在使用tight_layout时保持轴的长宽比

5

我有一个带有色条和图例的图表。我希望将图例放置在色条右侧的图表外面。为了实现这一目标,我使用了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() 的代码,但这会导致宽高比被扭曲:

宽高比失真的绘图

宽高比失真的绘图

如何显示整个图例并保留坐标轴的宽高比?


1
在这种情况下,您想要使图形更宽还是轴较小? - Paul H
1
(您还可以将图例移动到图形顶部) - Paul H
1个回答

2

您可以使用 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()

enter image description here


这个可以运行,但是它引入了另一个问题:现在色条比轴更高。 - Craig Sanders
尝试将 bottom = 0.2top = 0.8 参数传递给 subplots_adjustplt.subplots_adjust(left = 0.1, bottom = 0.2, top = 0.8)。您可能需要调整这些参数以优化结果。 - Zephyr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接