Subplots

Automatic figure size

By default, ProPlot automatically determines the suitable figure size given the geometry of your subplot grid and the size of a “reference” subplot. ProPlot can also determine the suitable figure height given a fixed figure width, and figure width given a fixed figure height.

This algorithm is controlled by the following subplots keyword arguments:

  • ref sets the reference subplot number (default is 1, i.e. the subplot in the upper left corner).

  • aspect sets the reference subplot aspect ratio (default is 1). You can also use the built-in matplotlib set_aspect method.

  • axwidth and axheight set the physical dimensions of the reference subplot (default is axwidth=2). If one is specified, the other is calculated to satisfy aspect. If both are specified, aspect is ignored. The dimensions of the figure are determined automatically.

  • width and height set the physical dimensions of the figure. If one is specified, the other is calculated to satisfy aspect and the subplot spacing. If both are specified (or if the matplotlib figsize parameter is specified), aspect is ignored.

  • journal constrains the physical dimensions of the figure so it meets requirements for submission to an academic journal. For example, figures created with journal='nat1' are sized as single-column Nature figures. See this table for the list of available journal specifications (feel free to add to this table by submitting a PR).

The below examples demonstrate the default behavior of the automatic figure sizing algorithm, and how it can be controlled with subplots keyword arguments.

Important

The automatic figure size algorithm has the following notable properties:

  • For very simple subplot grids (i.e. subplots created with the ncols and nrows arguments), the arguments aspect, axwidth, and axheight apply to every subplot in the figure – not just the reference subplot.

  • When the reference subplot aspect ratio has been fixed (e.g. with ax.set_aspect(1)) or is set to 'equal' (as with map projections and imshow images), the fixed aspect ratio is used and the subplots aspect parameter is ignored. This is critical for getting the figure size right when working with grids of images and grids of projections.

  • When colorbars and panels are present in the figure, their physical widths are preserved during figure resizing. ProPlot specifies their widths in physical units to help avoid colorbars that look “too skinny” or “too fat”.

  1. [1]:
  1. import proplot as plot
  2. import numpy as np
  3. # Auto sized grid of cartopy projections
  4. fig, axs = plot.subplots(ncols=2, nrows=3, proj='robin')
  5. axs.format(
  6. land=True, landcolor='k',
  7. suptitle='Auto figure sizing with grid of cartopy projections'
  8. )
  9. # Auto sized grid of images
  10. state = np.random.RandomState(51423)
  11. fig, axs = plot.subplots(ncols=3, nrows=2, axwidth=1.7)
  12. colors = state.rand(15, 12, 3).cumsum(axis=2)
  13. colors /= colors.max()
  14. axs.imshow(colors)
  15. axs.format(
  16. suptitle='Auto figure sizing with grid of images'
  17. )

_images/subplots_2_0.svg

_images/subplots_2_1.svg

  1. [2]:
  1. import proplot as plot
  2. # Change the reference subplot width
  3. suptitle = 'Effect of subplot width on figure size'
  4. for axwidth in ('4cm', '6cm'):
  5. fig, axs = plot.subplots(ncols=2, axwidth=axwidth,)
  6. axs[0].format(
  7. suptitle=suptitle,
  8. title=f'axwidth = {axwidth}', titleweight='bold',
  9. titleloc='uc', titlecolor='red9',
  10. )
  11. # Change the reference subplot aspect ratio
  12. for aspect in (1, (3, 2)):
  13. fig, axs = plot.subplots(ncols=2, nrows=2, axwidth=1.6, aspect=aspect)
  14. axs[0].format(
  15. suptitle='Effect of subplot aspect ratio on figure size',
  16. title=f'aspect = {aspect}', titleweight='bold',
  17. titleloc='uc', titlecolor='red9',
  18. )

_images/subplots_3_0.svg

_images/subplots_3_1.svg

_images/subplots_3_2.svg

_images/subplots_3_3.svg

  1. [3]:
  1. import proplot as plot
  2. # Change the reference subplot in presence of unequal width/height ratios
  3. for ref in (1, 2):
  4. fig, axs = plot.subplots(
  5. ref=ref, nrows=3, ncols=3, wratios=(3, 2, 2),
  6. axwidth=1.1,
  7. )
  8. axs[ref - 1].format(
  9. suptitle='Effect of reference subplot on figure size',
  10. title='reference', titleweight='bold',
  11. titleloc='uc', titlecolor='red9'
  12. )
  13. # Change the reference subplot in a complex grid
  14. for ref in (1, 2):
  15. fig, axs = plot.subplots(
  16. [[1, 2], [1, 3]],
  17. ref=ref, axwidth=1.8, span=False
  18. )
  19. axs[ref - 1].format(
  20. suptitle='Effect of reference subplot on figure size',
  21. title='reference', titleweight='bold',
  22. titleloc='uc', titlecolor='red9'
  23. )

_images/subplots_4_0.svg

_images/subplots_4_1.svg

_images/subplots_4_2.svg

_images/subplots_4_3.svg

Automatic subplot spacing

In addition to automatic figure sizing, by default ProPlot applies a tight layout algorithm to every figure. This algorithm automatically adjusts the space between subplot rows and columns and the figure edge to accommodate labels. It can be disabled by passing tight=False to subplots. While matplotlib has its own tight layout algorithm, ProPlot’s algorithm may change the figure size to accommodate the correct spacing and permits variable spacing between subsequent subplot rows and columns (see the new GridSpec class for details).

The tight layout algorithm can also be overridden. When you use any of the spacing arguments left, right, top, bottom, wspace, or hspace, that value is always respected. For example:

  • left='2em' fixes the left margin width, while the right, bottom, and top margin widths are determined automatically.

  • wspace='1em' fixes the spaces between subplot columns, while the spaces between subplot rows are determined automatically.

  • wspace=('3em', None) fixes the space between the first two columns of a three-column plot, while the space between the second two columns is determined automatically.

The below examples demonstrate how the tight layout algorithm permits variable spacing between subplot rows and columns.

  1. [4]:
  1. import proplot as plot
  2. # Automatic spacing for all margins and between all columns and rows
  3. fig, axs = plot.subplots(nrows=3, ncols=3, axwidth=1.1, share=0)
  4. # Formatting that stress-tests the algorithm
  5. axs[4].format(
  6. title='title\ntitle\ntitle',
  7. suptitle='Tight layout with variable row-column spacing'
  8. )
  9. axs[1].format(ylabel='ylabel\nylabel\nylabel')
  10. axs[:4:2].format(xlabel='xlabel\nxlabel\nxlabel')
  11. axs.format(
  12. rowlabels=['Row 1', 'Row 2', 'Row 3'],
  13. collabels=['Column 1', 'Column 2', 'Column 3']
  14. )

_images/subplots_6_0.svg

  1. [5]:
  1. import proplot as plot
  2. # Manual spacing for certain margins and between certain columns and rows
  3. fig, axs = plot.subplots(
  4. ncols=4, nrows=3, axwidth=1.1, span=False,
  5. bottom='5em', right='5em', # margin spacing overrides
  6. wspace=(0, 0, None), hspace=(0, None), # column and row spacing overrides
  7. )
  8. # Formatting that stress-tests the algorithm
  9. axs.format(
  10. xlim=(-1.5, 1.5), ylim=(-1.5, 1.5), xlocator=1, ylocator=1,
  11. suptitle='Tight layout with user overrides',
  12. rowlabels=['Row 1', 'Row 2', 'Row 3'],
  13. collabels=['Column 1', 'Column 2', 'Column 3', 'Column 4']
  14. )
  15. axs[0, :].format(xtickloc='top')
  16. axs[2, :].format(xtickloc='both')
  17. axs[:, 1].format(ytickloc='neither')
  18. axs[:, 2].format(ytickloc='right')
  19. axs[:, 3].format(ytickloc='both')
  20. axs[-1, :].format(title='Title\nTitle\nTitle', xlabel='xlabel')
  21. axs[:, 0].format(ylabel='ylabel\nylabel')

_images/subplots_7_0.svg

Axis sharing

Redundant labels are a common problem for figures with lots of subplots. To address this, matplotlib.pyplot.subplots includes sharex and sharey keywords that permit sharing axis limits, ticks, and tick labels between like rows and columns of subplots. ProPlot expands upon this feature by (1) adding an option for sharing labels in the same row or column of the GridSpec, controlled by the spanx and spany keywords, and (2) adding four axis-sharing “levels,” controlled by the sharex and sharey keywords. The axis-sharing levels are defined as follows:

  • Level 0 disables axis sharing.

  • Level 1 shares duplicate x and y axis labels, but nothing else.

  • Level 2 is the same as 1, but the x and y axis limits, ticks, and scales are also shared.

  • Level 3 is the same as 2, but the x and y tick labels are also shared.

Axis and label sharing works for arbitrarily complex grids of subplots. The below examples demonstrate the effect of various axis and label sharing settings on the appearance of simple subplot grids.

  1. [6]:
  1. import proplot as plot
  2. import numpy as np
  3. N = 50
  4. M = 40
  5. state = np.random.RandomState(51423)
  6. colors = plot.Colors('grays_r', M, left=0.1, right=0.8)
  7. datas = []
  8. for scale in (1, 3, 7, 0.2):
  9. data = scale * (state.rand(N, M) - 0.5).cumsum(axis=0)[N // 2:, :]
  10. datas.append(data)
  11. # Same plot with different sharing and spanning settings
  12. for share in (0, 1, 2, 3):
  13. fig, axs = plot.subplots(
  14. ncols=4, aspect=1, axwidth=1.06,
  15. sharey=share, spanx=share // 2
  16. )
  17. for ax, data in zip(axs, datas):
  18. on = ['off', 'on'][share // 2]
  19. ax.plot(data, cycle=colors)
  20. ax.format(
  21. suptitle=f'Sharing level {share}, spanning labels {on}',
  22. grid=False, xlabel='spanning', ylabel='shared'
  23. )

_images/subplots_9_0.svg

_images/subplots_9_1.svg

_images/subplots_9_2.svg

_images/subplots_9_3.svg

  1. [7]:
  1. import proplot as plot
  2. import numpy as np
  3. plot.rc.reset()
  4. plot.rc.cycle = 'Set3'
  5. state = np.random.RandomState(51423)
  6. titles = ['With redundant labels', 'Without redundant labels']
  7. # Same plot with and without default sharing settings
  8. for mode in (0, 1):
  9. fig, axs = plot.subplots(
  10. nrows=4, ncols=4, share=3 * mode,
  11. span=1 * mode, axwidth=1
  12. )
  13. for ax in axs:
  14. ax.plot((state.rand(100, 20) - 0.4).cumsum(axis=0))
  15. axs.format(
  16. xlabel='xlabel', ylabel='ylabel', suptitle=titles[mode],
  17. abc=True, abcloc='ul',
  18. grid=False, xticks=25, yticks=5
  19. )

_images/subplots_10_0.svg

_images/subplots_10_1.svg

A-b-c subplot labels

ProPlot can be used to add “a-b-c” labels to subplots. This is possible because subplots assigns unique numbers to each subplot. If you passed an array to subplots, the subplot numbers correspond to the numbers in the array. If you used the ncols and nrows keyword arguments, the number order is row-major by default but can be switched to column-major by passing order='F' to subplots. The number order also determines the subplot order in the SubplotsContainer returned by subplots.

To turn on “a-b-c” labels, set [rc.abc](https://proplot.readthedocs.io/en/latest/configuration.html?highlight=abc#rc-proplot) to True or pass abc=True to format (see the format command for details). To change the label style, modify [rc[‘abc.style’]](https://proplot.readthedocs.io/en/latest/configuration.html?highlight=abc.style#rc-proplot) or pass e.g. abcstyle='A.' to format. You can also modify the “a-b-c” label location, weight, and size with the [rc[‘abc.loc’]](https://proplot.readthedocs.io/en/latest/configuration.html?highlight=abc.loc#rc-proplot), [rc[‘abc.weight’]](https://proplot.readthedocs.io/en/latest/configuration.html?highlight=abc.weight#rc-proplot), and [rc[‘abc.size’]](https://proplot.readthedocs.io/en/latest/configuration.html?highlight=abc.size#rc-proplot) settings.

  1. [8]:
  1. import proplot as plot
  2. fig, axs = plot.subplots(nrows=8, ncols=8, axwidth=0.7, space=0)
  3. axs.format(
  4. abc=True, abcloc='ur', xlabel='x axis', ylabel='y axis',
  5. xticks=[], yticks=[], suptitle='Subplot labels demo'
  6. )

_images/subplots_12_0.svg

Arbitrary physical units

ProPlot supports arbitrary physical units for controlling the figure width and height, the reference subplot axwidth and axheight, the gridspec spacing values left, right, bottom, top, wspace, and hspace, and in a few other places, e.g. panel and colorbar widths. This feature is powered by the units function.

If a sizing argument is numeric, the units are inches or points; if it is string, the units are converted to inches or points by units. A table of acceptable units is found in the units documentation. They include centimeters, millimeters, pixels, em-heights), en-heights), and points).

  1. [9]:
  1. import proplot as plot
  2. import numpy as np
  3. with plot.rc.context(fontsize='12px'):
  4. fig, axs = plot.subplots(
  5. ncols=3, width='15cm', height='3in',
  6. wspace=('10pt', '20pt'), right='10mm'
  7. )
  8. cmap = plot.Colormap('Mono')
  9. cb = fig.colorbar(
  10. cmap, loc='b', extend='both', label='colorbar',
  11. width='2em', extendsize='3em', shrink=0.8,
  12. )
  13. pax = axs[2].panel('r', width='5en')
  14. pax.format(xlim=(0, 1))
  15. axs.format(
  16. suptitle='Arguments with arbitrary units',
  17. xlabel='x axis', ylabel='y axis',
  18. xlim=(0, 1), ylim=(0, 1),
  19. )

_images/subplots_14_0.svg