[Python] How to automatically set number of rows & columns subplots

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have a certain amount of figures I want to generate and organize in subplots, and I would like to automatically find the amount of columns and rows to specify in my subplots. So far the best way I found was to calculate the square root of my total amount of subplots, round it to the upper int, and automatically delete the empty subplots. But this method is not the best when the amount of subplots increases. Do you know of a better way to do this ?

    import numpy as np
    import matplotlib.pylab as plt


    percentile = np.linspace(0.1,0.9,10)
    test = np.linspace(0,10,123)
    nb = int(np.sqrt(len(percentile))) + 1

    # the "test" variable is not important. The "percentile" dictates how many subplots I want

    fig, axs = plt.subplots(nb,nb, figsize=(15, 15), facecolor='w', edgecolor='k')

    count = 0
    for l in range(0,nb):
    for c in range(0,nb):

    if count < len(percentile):
    axs[l,c].plot(test*percentile[count])

    else:
    axs[l,c].set_visible(False)

    count = count + 1

    Continue reading...

Compartilhe esta Página