I’m generating a figure with a variable number of plots. At the moment, if I use a number of plots that is not a multiple of three, the final plot(s) is left-aligned:
Here’s my plotting function:
def mag_dist(dataset, magnames):
num_magnames = len(magnames)
num_cols = 3 if num_magnames > 3 else num_magnames
num_rows = (num_magnames + num_cols - 1) // num_cols
color = iter(cm.rainbow(np.linspace(0, 1, num_magnames)))
fig, axs = plt.subplots(num_rows, num_cols, figsize=(12, 4*num_rows), sharex=True, sharey=True)
axs = np.array(axs).reshape(num_rows, num_cols)
for i, band in enumerate(magnames):
bins = 50
alpha = 1
density = True
row = i // num_cols
col = i % num_cols
ax = axs[row, col]
counts, bins, _ = ax.hist(dataset[band], bins=bins, alpha=alpha, density=density, color=next(color), linewidth=3)
ax.grid(True)
ax.set_xlabel('')
ax.set_yscale('log')
max_x = np.max(dataset[band])
ax.text(0.95, 0.95, f'Max: {max_x:.2f}', ha='right', va='top', transform=ax.transAxes, color='black', fontsize=15)
# Remove empty subplots
for j in range(i + 1, num_rows * num_cols):
fig.delaxes(axs.flatten()[j])
# Adjust layout for single and double plots (Copilot helped me with this bit)
if num_magnames == 1:
ax = axs.flatten()[0]
ax.set_position([0.3, 0.3, 0.4, 0.4]) # Center the single plot
elif num_magnames == 2:
ax1, ax2 = axs.flatten()[:2]
ax1.set_position([0.1, 0.3, 0.35, 0.4]) # Space the first plot
ax2.set_position([0.55, 0.3, 0.35, 0.4]) # Space the second plot
plt.tight_layout(pad=3.0)
plt.show()
Here’s what I’m trying to achieve:
- if there is only one plot left after deleting the unused ones, center it in the figure, and
- if there are two plots, space them out evenly along the bottom row.
Is there any way to do this?