Matplotlib: Repositioning a subplot in a grid of subplots

前端 未结 2 1977
鱼传尺愫
鱼传尺愫 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 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

提交回复
热议问题