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

如何绘制2D图像并对齐轴投影,缩小投影尺寸以让图像占主要空间

调整Matplotlib投影图尺寸并保持与图像对齐

要实现缩小投影图尺寸同时保持和图像的完美对齐,核心是调整gridspec.GridSpec的比例参数,给投影图的占比设置一个小于1的缩放因子,同时保留图像的宽高比关联逻辑。

修改后的代码

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from skimage import data

img = data.coins()
h, w = img.shape
ratio = h/w
# 缩放因子,越小投影图尺寸越小,可根据需求调整
scale = 0.2

fig = plt.figure(figsize=(8, 8))
# 调整宽度和高度比例:投影图占比 = 原比例 * 缩放因子
gs = gridspec.GridSpec(2, 2, 
                       width_ratios=[ratio * scale, 1], 
                       height_ratios=[(1/ratio) * scale, 1])

# 中心图像轴
ax_center = plt.subplot(gs[1, 1])
ax_center.imshow(img)
# 隐藏图像轴的刻度,让布局更整洁
ax_center.set_xticks([])
ax_center.set_yticks([])

# 左侧投影图轴
ax_left = plt.subplot(gs[1, 0])
ax_left.set_title('Left Plot')
ax_left.plot(-img.mean(axis=1), range(img.shape[0]))
# 对齐图像y轴,隐藏x轴刻度和边框
ax_left.set_xlim(-img.mean(axis=1).max(), 0)
ax_left.set_ylim(ax_center.get_ylim())
ax_left.set_xticks([])
ax_left.spines[['top', 'right', 'bottom']].set_visible(False)

# 顶部投影图轴
ax_top = plt.subplot(gs[0, 1])
ax_top.set_title('Top Plot')
ax_top.plot(img.mean(axis=0))
# 对齐图像x轴,隐藏y轴刻度和边框
ax_top.set_ylim(0, img.mean(axis=0).max())
ax_top.set_xlim(ax_center.get_xlim())
ax_top.set_yticks([])
ax_top.spines[['top', 'right', 'left']].set_visible(False)

plt.tight_layout()
plt.show()

关键修改说明

  • 缩放因子scale:通过这个参数控制投影图的尺寸,数值越小,左侧投影图越窄、顶部投影图越矮,取值范围建议在0.1-0.5之间。
  • GridSpec比例调整:将投影图的比例设置为原比例 * scale,确保投影图和图像的宽高比关联,从而保持对齐。
  • 坐标轴对齐优化:通过ax_center.get_xlim()和ax_center.get_ylim()获取图像轴的范围,同步到投影图轴上,保证完全对齐;同时隐藏投影图的多余边框和刻度,提升视觉效果。

内容的提问来源于stack exchange,提问作者G M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 03:11:16