With newer versions of matplotlib (since 3.4.0), you can use an array of strings to design your subplots pattern (rows and columns) and use it to create the figure by calling matplotlib.pyplot.subplot_mosaic.
Instead of cfig, ax = plt.subplots(3,2)
, use cfig, axs = plt.subplot_mosaic(mosaic)
and define mosaic
this way:
mosaic = [['a', 'b'],
['c', 'd'],
['e', '.']]
In this pattern, blank subplots are denoted by '.'
(by default, this can be parametrized in the call). You do not need to delete blank subplots, as they are not even created.
To select an axis for plotting, just use axs[id]
where id
is the string used to identify the subplot in the mosaic array.
Example:
mosaic = [['b', 'a'], ['.', 'au']]
kw = dict(layout='constrained')
fig, axs = plt.subplot_mosaic(mosaic, **kw)
ax = axs['b']
ax.grid(axis='y')
ax.bar(n, d)
ax = axs['a']
ax.grid(axis='y')
ax.bar(n, prior)
[...]
With subplot_mosaic
, not only you can introduce blank subplots, but you can also merge 'cells' in order to create subplots on multiple rows and/or columns, just by crafting the required mosaic array, the rest of the code is unchanged. In addtion mosaic
doesn't need to be an array, it can also be a multiline string. E.g. from Complex and semantic figure composition, using:
"""
A.C
BBB
.D.
"""
results in: