1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
|
.. _plotting-guide-tight-layout:
******************
Tight Layout guide
******************
*tight_layout* automatically adjusts subplot params so that the
subplot(s) fits in to the figure area. This is an experimental
feature and may not work for some cases. It only checks the extents
of ticklabels, axis labels, and titles.
Simple Example
==============
In matplotlib location of axes (including subplots) are specified in
normalized figure coordinate. It can happen that your axis labels or
titles (or sometimes even ticklabels) go outside the figure area thus
clipped.
.. plot::
:include-source:
:context:
plt.rcParams['savefig.facecolor'] = "0.8"
def example_plot(ax, fontsize=12):
ax.plot([1, 2])
ax.locator_params(nbins=3)
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
plt.close('all')
fig, ax = plt.subplots()
example_plot(ax, fontsize=24)
To prevent this, the location of axes need to be adjusted. For
subplots, this can be done by adjusting the subplot params
(:ref:`howto-subplots-adjust`). Matplotlib v1.1 introduces a new
command :func:`~matplotlib.pyplot.tight_layout` that does this
automatically for you.
.. plot::
:include-source:
:context:
plt.tight_layout()
When you have multiple subplots, often you see labels of different
axes overlaps each other.
.. plot::
:include-source:
:context:
plt.close('all')
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
*tight_layout* will also adjust spacing betweens subplots to minimize
the overlaps.
.. plot::
:include-source:
:context:
plt.tight_layout()
:func:`~matplotlib.pyplot.tight_layout` can take keyword arguments of
*pad*, *w_pad* and *h_pad*. These controls the extra pad around the
figure border and between subplots. The pads are specified in fraction
of fontsize.
.. plot::
:include-source:
:context:
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
:func:`~matplotlib.pyplot.tight_layout` will work even if the sizes of
subplot are different as far as their grid specification is
compatible. In the example below, *ax1* and *ax2* are subplots of 2x2
grid, while *ax3* is of 1x2 grid.
.. plot::
:include-source:
:context:
plt.close('all')
fig = plt.figure()
ax1 = plt.subplot(221)
ax2 = plt.subplot(223)
ax3 = plt.subplot(122)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
plt.tight_layout()
It works with subplots created with
:func:`~matplotlib.pyplot.subplot2grid`. In general, subplots created
from the gridspec (:ref:`gridspec-guide`) will work.
.. plot::
:include-source:
:context:
plt.close('all')
fig = plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0))
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout()
Although not thoroughly tested, it seems to work for subplots with
aspect != "auto" (e.g., axes with images).
.. plot::
:include-source:
:context:
arr = np.arange(100).reshape((10,10))
plt.close('all')
fig = plt.figure(figsize=(5,4))
ax = plt.subplot(111)
im = ax.imshow(arr, interpolation="none")
plt.tight_layout()
Caveats
-------
* *tight_layout* only considers ticklabels, axis labels, and titles. Thus, other atists may be clipped and also may overlap.
* It assumes that the extra space needed for ticklabels, axis labels,
and titles is independent of original location of axes. This is
often True, but there are rare cases it is not.
* pad=0 clips some of the texts by a few pixels. This may be a bug or
a limitation of the current algorithm and it is not clear why it
happens. Meanwhile, use of pad at least larger than 0.3 is
recommended.
Use with GridSpec
-----------------
GridSpec has its own tight_layout method
(the pyplot api :func:`~matplotlib.pyplot.tight_layout` also works).
.. plot::
:include-source:
:context:
plt.close('all')
fig = plt.figure()
import matplotlib.gridspec as gridspec
gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
example_plot(ax1)
example_plot(ax2)
gs1.tight_layout(fig)
You may provide an optional *rect* parameter, which specify the bbox
that the subplots will be fit in. The coordinate must be in normalized
figure coordinate and the default is (0, 0, 1, 1).
.. plot::
:include-source:
:context:
gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])
For example, this can be used for a figure with multiple grid_spec's.
.. plot::
:include-source:
:context:
gs2 = gridspec.GridSpec(3, 1)
for ss in gs2:
ax = fig.add_subplot(ss)
example_plot(ax)
ax.set_title("")
ax.set_xlabel("")
ax.set_xlabel("x-label", fontsize=12)
gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5)
We may try to match the top and bottom of two grids ::
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)
gs1.update(top=top, bottom=bottom)
gs2.update(top=top, bottom=bottom)
While this should be mostly good enough, but adjusting top and bottom
may requires adjustment in hspace also. To update hspace & vspace, we
call tight_layout again with updated rect argument. Note the rect
argument specifies area including the ticklabels etc. Thus we will
increase the bottom (which is 0 in normal case) by the difference
between the *bottom* from above and bottom of each gridspec. Same
thing for top.
.. plot::
:include-source:
:context:
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)
gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom),
0.5, 1 - (gs1.top-top)])
gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom),
None, 1 - (gs2.top-top)],
h_pad=0.5)
Use with AxesGrid1
------------------
While limited, axes_grid1 toolkit is also supported.
.. plot::
:include-source:
:context:
plt.close('all')
fig = plt.figure()
from mpl_toolkits.axes_grid1 import Grid
grid = Grid(fig, rect=111, nrows_ncols=(2,2),
axes_pad=0.25, label_mode='L',
)
for ax in grid:
example_plot(ax)
ax.title.set_visible(False)
plt.tight_layout()
Colorbar
--------
If you create colorbar with :func:`~matplotlib.pyplot.colorbar`
command, the created colorbar is an instance of Axes not Subplot, thus
tight_layout does not work. With Matplotlib v1.1, you may create a
colobar as a subplot using the gridspec.
.. plot::
:include-source:
:context:
plt.close('all')
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none")
plt.colorbar(im, use_gridspec=True)
plt.tight_layout()
Another option is to use AxesGrid1 toolkit to
explicitly create an axes for colorbar.
.. plot::
:include-source:
:context:
plt.close('all')
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none")
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", "5%", pad="3%")
plt.colorbar(im, cax=cax)
plt.tight_layout()
|