Search code examples
pythonloopsmatplotlibsizesubplot

Size of subplots in loop: Python


I have a loop generating a varying amount of subplots in a (nx3) pattern, where n is increasing relative to amount of subplots. I want to fix the size of every subplot (all of equal size), to be sure they are outputted nicely.

My code is part of a larger script but here's is the subplotting loop:

for i in range(len(iters)):                                             # range(amount of iterations)
            iter = int(iters[i])

            plt.subplot(n, 3, i+1)
            # plotting and scaling accordingly to iteration:
            scaleFactor = frac**(len(iters)-i-1)
            plt.plot(points[0, :iter]/scaleFactor, points[1, :iter]/scaleFactor, 'b-', linewidth=1)
            plt.xlim([0, 1])
            plt.ylim([-0.25, 0.525])
            plt.title('Iteration %i' %i)
            plt.xlabel('x')
            plt.ylabel('y')
     
      plt.show()

Solution

  • Have you tried the gridspec package before? It gives pretty good control over the size and spacing of subplots. You start by defining the grid object (gs) then just pick out the part of the grid you want to work with in the call to add_subplot.

    from matplotlib import gridspec
    
    iters = 'abcdefghijklmnop' ### left image in example output
    
    ### right image in example output
    # iters = 'abcdefghijklmnopqrstuvwxyz' 
    
    rows = int(len(iters)/3)+1
    fig = plt.figure(figsize=(6, 1.2*rows))
    gs = gridspec.GridSpec(rows, 3, wspace=0.25, hspace=0.45)
    
    for i in range(len(iters)):
        ax = fig.add_subplot(gs[i])
        ax.plot([1,2], [2,1])
    plt.show()
    

    enter image description here