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

去除Matplotlib 3D子图顶部与左侧多余边距的方法

问题描述

我绘制了一组包含3D投影子图的图表,其他图表显示正常,但3D子图的顶部和左侧存在大量空白区域(底部和右侧边距无异常)。尝试手动调整边距(原边距值0.5, 0.5, 0)、修改matplotlib配置savefig.bbox = tight都没解决问题,且单独绘制3D图无此问题。

补充说明

  • 尝试过调整subplots_adjust的left参数,但会破坏非3D子图的布局,无法适用当前场景。
解决方案

问题根源是3D子图的轴边界计算逻辑和2D子图不兼容,tight_layout()无法自动适配混合子图的布局。可以通过单独调整3D子图的位置参数,既消除多余空白,又不影响2D子图的正常布局。

修改后的代码

import matplotlib
matplotlib.use('agg')

import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure()
# 创建3D子图并保留引用
ax3d = fig.add_subplot(2, 1, 1, projection='3d')

x_labels = [10,20,30]
x = [1,2,3,4]
y = [3,1,5,1]

for label in x_labels:
    x_3d = label * np.ones_like(x)
    ax3d.plot(x_3d, x, y, color='black')

ax3d.set_zlabel('test')

# 创建2D子图
ax2d = fig.add_subplot(2, 1, 2)
time = np.arange(0, 10, 0.1)
ax2d.plot(time, np.sin(time))

# 先让tight_layout优化整体布局
fig.tight_layout()

# 单独调整3D子图位置,消除左侧和顶部空白
# 获取子图当前位置:[left, bottom, width, height](相对画布的比例,0-1)
pos = ax3d.get_position()
# 左移子图减少左侧空白,拉高子图高度减少顶部空白
ax3d.set_position([pos.x0 + 0.08, pos.y0, pos.width, pos.height + 0.05])

canvas = FigureCanvas(fig)
canvas.print_figure(r'D:\test.png')

关键说明

  • get_position()返回子图的位置坐标列表,[left, bottom, width, height]的取值范围为0到1,代表相对整个画布的比例
  • 调整参数时:
    • 增大pos.x0的值可左移3D子图,减少左侧空白
    • 增大pos.height的值可拉高3D子图,减少顶部空白
    • 可根据实际空白程度微调数值,确保视觉效果自然
  • 该方法仅修改3D子图的位置,不会影响2D子图的布局,完美适配混合子图场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:10:27