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

使用Matplotlib曲线坐标轴时出现异常边距问题求助

Matplotlib曲线网格图边距异常的解决尝试方案

这个来自Matplotlib官方文档的示例代码,在Jupyter Lab中运行后图像上下边距异常;在标准Python解释器中运行时,上下边距过大且右边距明显异常。已经尝试在plt.show()前调用plt.tight_layout()但无效果,查看Axes/HostAxes源码也未找到明确解决方向,以下是一些可行的解决尝试方案:

示例代码

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
from mpl_toolkits.axisartist import Axes, HostAxes, angle_helper
from mpl_toolkits.axisartist.grid_helper_curvelinear import \
    GridHelperCurveLinear


def curvelinear_test1(fig):
    """
    Grid for custom transform.
    """

    def tr(x, y): return x, y - x
    def inv_tr(x, y): return x, y + x

    grid_helper = GridHelperCurveLinear((tr, inv_tr))

    ax1 = fig.add_subplot(1, 2, 1, axes_class=Axes, grid_helper=grid_helper)
    # ax1 will have ticks and gridlines defined by the given transform (+ transData of the Axes).  Note that the transform of the Axes itself (i.e., transData) is not affected by the given transform.
    xx, yy = tr(np.array([3, 6]), np.array([5, 10]))
    ax1.plot(xx, yy)

    ax1.set_aspect(1)
    ax1.set_xlim(0, 10)
    ax1.set_ylim(0, 10)

    ax1.axis["t"] = ax1.new_floating_axis(0, 3)
    ax1.axis["t2"] = ax1.new_floating_axis(1, 7)
    ax1.grid(True, zorder=0)

fig = plt.figure()
curvelinear_test1(fig)
plt.show()

运行异常效果

Jupyter Lab运行结果

Jupyter Lab运行结果

标准Python解释器运行结果

标准Python运行结果

可行解决尝试方案

  • 手动调整子图布局参数:调用fig.subplots_adjust()直接控制边距,根据实际效果修改数值:

    fig.subplots_adjust(left=0.15, right=0.85, top=0.85, bottom=0.15)
    
  • 直接指定子图位置尺寸:跳过自动布局,手动定义子图在画布中的位置和大小(参数范围0-1):

    ax1.set_position([0.1, 0.1, 0.7, 0.8])
    
  • 排查自定义变换的影响:自定义变换函数可能导致轴范围计算异常,先打印实际轴范围确认:

    print("X范围:", ax1.get_xlim())
    print("Y范围:", ax1.get_ylim())
    

    若与设置的(0,10)不符,尝试修正变换函数或重新调整轴范围。

  • 替换axisartist的Axes为普通Axes:axisartist模块的Axes类和默认布局兼容性较差,尝试去掉axes_class=Axes参数:

    ax1 = fig.add_subplot(1, 2, 1, grid_helper=grid_helper)
    

    注意此操作可能影响自定义网格显示,需测试效果。

  • 调整tight_layout参数:尝试指定pad或rect参数强制调整布局:

    plt.tight_layout(pad=3.0, rect=[0, 0, 0.9, 1])
    
  • 隐藏多余浮动轴:如果不需要浮动轴t和t2,隐藏它们以释放布局空间:

    ax1.axis["t"].set_visible(False)
    ax1.axis["t2"].set_visible(False)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 11:10:37