You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib使用tight_layout时如何保留坐标轴纵横比并完整显示图例

解决方案

你可以通过以下两种方法实现需求,两种方案都不会改变坐标轴原有纵横比:

方案1:手动预留右侧空间

通过subplots_adjust方法手动设置子图右侧边界,给颜色条和图例预留足够的显示空间,无需修改其他逻辑。仅需在plt.show()前添加一行代码:

plt.subplots_adjust(right=0.8)

数值0.8可根据图例的实际宽度灵活调整,数值越小代表右侧预留的空白空间越大。

方案2:tight_layout指定额外计算元素

如果要使用tight_layout的自动适配能力,可以在调用时传入图例、颜色条这两个额外的绘图元素,让tight_layout在计算布局时将这两个元素纳入考虑,不会挤压主图区域。
修改代码如下:

# 先将图例赋值给变量
leg = plt.legend(loc="center left", bbox_to_anchor=(1.3, 0.5))
# 调用tight_layout时传入额外元素
plt.tight_layout(bbox_extra_artists=(leg, colorbar))

完整可运行代码

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])
# 如果需要强制固定坐标轴等比例,将aspect="auto"改为aspect=1即可
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",
)
leg = plt.legend(loc="center left", bbox_to_anchor=(1.3, 0.5))
# 以下二选一即可
# 方案1:手动预留空间
# plt.subplots_adjust(right=0.8)
# 方案2:带参数的tight_layout
plt.tight_layout(bbox_extra_artists=(leg, colorbar))
# 原代码plt.title漏了调用括号,需要加标题请参考下方写法
# plt.title("概率分布示例")
plt.show()

内容的提问来源于stack exchange,提问作者Craig Sanders

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:48:04