【问题标题】:Python subplots leaving space for common axis labelsPython 子图为公共轴标签留出空间
【发布时间】:2012-12-15 11:38:46
【问题描述】:

我有以下代码在一个图中制作四个子图:

f = figure( figsize=(7,7) )
f.add_axes([0.2,0.175,0.75,0.75])
f.subplots_adjust(left=0.15)
f.clf()
ax = f.add_subplot(111)
ax1 = f.add_subplot(221)
ax2 = f.add_subplot(222)
ax3 = f.add_subplot(223)
ax4 = f.add_subplot(224)
ax.xaxis.set_major_formatter( NullFormatter() )
ax.yaxis.set_major_formatter( NullFormatter() )
ax2.xaxis.set_major_formatter( NullFormatter() )
ax2.yaxis.set_major_formatter( NullFormatter() )
ax1.xaxis.set_major_formatter( NullFormatter() )
ax4.yaxis.set_major_formatter( NullFormatter() )
f.subplots_adjust(wspace=0,hspace=0)

ax1.plot(tbins[0:24], mean_yszth1, color='r', label='mean', marker='.', lw=3)
ax2.plot(tbins[0:24], mean_ysz1, color='r', label='mean', marker='.', lw=3)
ax3.plot(tbins[0:24], mean_yszth2, color='r', label='mean', marker='.', lw=3)
ax4.plot(tbins[0:24], mean_ysz2, color='r', label='mean', marker='.', lw=3)

ax1.set_xlim(0,12)
ax1.set_ylim(-0.5,0.5)
ax2.set_xlim(0,12)
ax2.set_ylim(-0.5,0.5)
ax3.set_xlim(0,12)
ax3.set_ylim(-0.5,0.5)
ax4.set_xlim(0,12)
ax4.set_ylim(-0.5,0.5)
ax.set_xlabel(r"$\mathrm{Time\ since\ last\ merger\ (Gyr)}$")
ax.set_ylabel(r"$\mathrm{\Delta Y_{SZ}/Y_{SZ}}$")

结果如下所示:

如您所见,轴标签与刻度重叠。我想将公共轴标签从轴上移开一点。我不知道如何最好地做到这一点。

【问题讨论】:

    标签: python matplotlib axis-labels subplot


    【解决方案1】:

    使用set_ylabelset_xlabel 方法的labelpad 参数:

    Definition: ax.set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs)
    Docstring:
    Call signature::
    
      set_ylabel(ylabel, fontdict=None, labelpad=None, **kwargs)
    
    Set the label for the yaxis
    
    *labelpad* is the spacing in points between the label and the y-axis
    

    这是我将 labelpad 设置为 50 (x) 和 60 (y) 的结果。使用默认配置时,我不得不手动修改图形边距,因为标签位于图形框架之外。

    编辑
    从您的 cmets 看来,您可能正在使用一个非常旧版本的 matplotlib。 Labelpad 参数从许多版本开始就在 matplotlib 中,但设置它的方式可能不同(我不确定)。
    在网上我发现some comments 指向这种用法:

    ax.xaxis.LABELPAD = 8  # default is 5
    

    我也见过这样的:

    ax.xaxis.labelpad = 8
    

    【讨论】:

    • 这就是我所做的:ax.set_ylabel(ylabel, labelpad=10)。但我收到一条错误消息Unknown property labelpad。也许我的 Python 版本太旧了?
    • 您使用的是哪个版本?它适用于您在 mpl 与 1.2.0(Windows 7 64 位)上的图形设置。但我认为这个参数在以前的版本中也应该可以工作(至少 mpl 0.99.1)
    • 上面写着 Python 2.5.4。我还在错误消息中找到了这一行:/scisoft/lib/python2.5/site-packages/matplotlib/axes.pyc in set_xlabel(self, xlabel, fontdict, **kwargs)。我正在使用的版本中似乎没有标签板。
    • 您的错误似乎表明您正在使用版本不高于 7.3(具有 python 2.5)的 scisoft 包。此版本使用 matplotlib 0.98.5,这是一个非常旧的版本(超过 3 年)。您应该更新到后一个 scisoft 版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 2014-05-01
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    相关资源
    最近更新 更多