OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Adjusting figure to center plots along bottom row

  • Thread starter Thread starter Jim421616
  • Start date Start date
J

Jim421616

Guest
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: enter image description here

Here's my plotting function:

Code:
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?
<p>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:
<a href="https://i.sstatic.net/nKevFrPN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/nKevFrPN.png" alt="enter image description here" /></a></p>
<p>Here's my plotting function:</p>
<pre><code>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()
</code></pre>
<p>Here's what I'm trying to achieve:</p>
<ul>
<li>if there is only one plot left after deleting the unused ones, center it in the figure, and</li>
<li>if there are two plots, space them out evenly along the bottom row.</li>
</ul>
<p>Is there any way to do this?</p>
 

Latest posts

Top