How to make more than 10 subplots in a figure?

前端 未结 1 862
花落未央
花落未央 2021-02-03 11:22

I am trying to make a 5x4 grid of subplots, and from looking at examples it seems to me that the best way is:

import matplotlib.pyplot as plt
plt.figure()
plt.su         


        
1条回答
  •  星月不相逢
    2021-02-03 11:37

    You are probably looking for GridSpec. You can state the size of your grid (5,4) and the position for each plot (row = 0, column = 2, i.e. - 0,2). Check the following example:

    import matplotlib.pyplot as plt
    
    plt.figure(0)
    ax1 = plt.subplot2grid((5,4), (0,0))
    ax2 = plt.subplot2grid((5,4), (1,1))
    ax3 = plt.subplot2grid((5,4), (2, 2))
    ax4 = plt.subplot2grid((5,4), (3, 3))
    ax5 = plt.subplot2grid((5,4), (4, 0))
    plt.show()
    

    , which results in this:

    Should you build nested loops to make your full grid:

    import matplotlib.pyplot as plt
    
    plt.figure(0)
    for i in range(5):
        for j in range(4):
            plt.subplot2grid((5,4), (i,j))
    plt.show()
    

    , you'll obtain this:

    The plots works the same as in any subplot (call it directly from the axes you've created):

    import matplotlib.pyplot as plt
    import numpy as np
    
    plt.figure(0)
    plots = []
    for i in range(5):
        for j in range(4):
            ax = plt.subplot2grid((5,4), (i,j))
            ax.scatter(range(20),range(20)+np.random.randint(-5,5,20))
    plt.show()
    

    , resulting in this:

    Notice that you can provide different sizes to plots (stating number of columns and rows for each plot):

    import matplotlib.pyplot as plt
    
    plt.figure(0)
    ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
    ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
    ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2)
    ax4 = plt.subplot2grid((3,3), (2, 0))
    ax5 = plt.subplot2grid((3,3), (2, 1))
    plt.show()
    

    , therefore:

    In the link I gave in the beginning you will also find examples to remove labels among other stuff.

    0 讨论(0)
提交回复
热议问题