Python subplots leaving space for common axis labels

陌路散爱 提交于 2019-12-14 01:35:56

问题


I have the following code that makes four subplots in one figure:

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}}$")

The result looks like this:

As you can see, the axis labels overlap with the ticks. I would like to move the common axis labels away from the axes a little. I can't figure out how best to do this.


回答1:


Use labelpad parameter of set_ylabel and set_xlabel methods:

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

This is what I get with labelpad set to 50 (x) and 60 (y). I had to modify manually figure margins as the labels were outside the figure frame when using the default configuration.

Edit
From your comments it seems you could be using a very old version of matplotlib. Labelpad parameter has been in matplotlib from many versions ago but the way to of setting it could be different (I do not know for sure).
In the web I found some comments that point to this usage:

ax.xaxis.LABELPAD = 8  # default is 5

also I have seen it like:

ax.xaxis.labelpad = 8


来源:https://stackoverflow.com/questions/14099435/python-subplots-leaving-space-for-common-axis-labels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!