Last active
March 15, 2022 10:41
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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