Skip to content

Instantly share code, notes, and snippets.

@IgnacioHeredia
Last active March 15, 2022 10:41
Show Gist options
  • Save IgnacioHeredia/cc71535f7c8b5e84d940c82b3c472498 to your computer and use it in GitHub Desktop.
Save IgnacioHeredia/cc71535f7c8b5e84d940c82b3c472498 to your computer and use it in GitHub Desktop.
Modification of matplotlib plt.subplots(), useful when some subplots are empty. It returns a grid where the plots in the last row are centered.
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
def subplots_centered(nrows, ncols, figsize, nfigs):
"""
Modification of matplotlib plt.subplots(),
useful when some subplots are empty.
It returns a grid where the plots
in the **last** row are centered.
Inputs
------
nrows, ncols, figsize: same as plt.subplots()
nfigs: real number of figures
"""
assert nfigs < nrows * ncols, "No empty subplots, use normal plt.subplots() instead"
fig = plt.figure(figsize=figsize)
axs = []
m = nfigs % ncols
m = range(1, ncols+1)[-m] # subdivision of columns
gs = gridspec.GridSpec(nrows, m*ncols)
for i in range(0, nfigs):
row = i // ncols
col = i % ncols
if row == nrows-1: # center only last row
off = int(m * (ncols - nfigs % ncols) / 2)
else:
off = 0
ax = plt.subplot(gs[row, m*col + off : m*(col+1) + off])
axs.append(ax)
return fig, axs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment