loop over 2d subplot as if it's a 1-D

前端 未结 2 1286
攒了一身酷
攒了一身酷 2021-02-20 06:33

I\'m trying to plot many data using subplots and I\'m NOT in trouble but I\'m wondering if there is a convenience method to do this.

below is the sample code.

         


        
2条回答
  •  遥遥无期
    2021-02-20 06:55

    Rather than creating your subplots in advance using plt.subplots, just create them as you go using plt.subplot(nrows, ncols, number). The small example below shows how to do it. It's created a 3x3 array of plots and only plotted the first 6.

    import numpy as np
    import matplotlib.pyplot as plt
    
    nrows, ncols = 3, 3
    
    x = np.linspace(0,10,100)
    
    fig = plt.figure()    
    for i in range(1,7):
        ax = fig.add_subplot(nrows, ncols, i)
        ax.plot(x, x**i)
    
    plt.show()
    

    Example

    You could fill the final three in of course by doing plt.subplot(nrows, ncols, i) but not calling any plotting in there (if that's what you wanted).

    import numpy as np
    import matplotlib.pyplot as plt
    
    nrows, ncols = 3, 3
    
    x = np.linspace(0,10,100)
    
    fig = plt.figure()    
    for i in range(1,10):
        ax = fig.add_subplot(nrows, ncols, i)
        if i < 7:
            ax.plot(x, x**i)
    
    plt.show()
    

    Example 2

    You may also like the look of GridSpec.

提交回复
热议问题