Matplotlib: Repositioning a subplot in a grid of subplots

前端 未结 2 1973
鱼传尺愫
鱼传尺愫 2021-02-08 20:40

I am trying to make a plot with 7 subplots. At the moment I am plotting two columns, one with four plots and the other with three, i.e. like this:

相关标签:
2条回答
  • 2021-02-08 20:56

    Use grid spec (doc) with a 4x4 grid, and have each plot span 2 columns as such:

    import matplotlib.gridspec as gridspec
    gs = gridspec.GridSpec(4, 4)
    ax1 = plt.subplot(gs[0, 0:2])
    ax2 = plt.subplot(gs[0,2:])
    ax3 = plt.subplot(gs[1,0:2])
    ax4 = plt.subplot(gs[1,2:])
    ax5 = plt.subplot(gs[2,0:2])
    ax6 = plt.subplot(gs[2,2:])
    ax7 = plt.subplot(gs[3,1:3])
    fig = gcf()
    gs.tight_layout(fig)
    ax_lst = [ax1,ax2,ax3,ax4,ax5,ax6,ax7]
    
    0 讨论(0)
  • 2021-02-08 21:12

    If you want to keep the for loop, you can arrange your plots with subplot2grid, which allows for a colspan parameter:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.random.rand(20)
    y = np.random.rand(20)
    fig = plt.figure(figsize=(6.5,12))
    plt.subplots_adjust(wspace=0.2,hspace=0.2)
    iplot = 420
    for i in range(7):
        iplot += 1
        if i == 6:
            ax = plt.subplot2grid((4,8), (i//2, 2), colspan=4)
        else:
            # You can be fancy and use subplot2grid for each plot, which doesn't
            # require keeping the iplot variable:
            # ax = plt.subplot2grid((4,2), (i//2,i%2))
    
            # Or you can keep using add_subplot, which may be simpler:
            ax = fig.add_subplot(iplot)
        ax.plot(x,y,'ko')
        ax.set_xlabel("x")
        ax.set_ylabel("y")
    plt.savefig("subplots_example.png",bbox_inches='tight')
    

    subplots in a grid with colspan

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