Dawei Wang
Dawei Wang

Reputation: 176

Subplot and share y-axis in a 4-by-n grid

I'm trying to define a function that can plot subplots within a 4-by-n grid. The code below works but I want to make the subplots share y axis, which I think I (definitely?) have to use the method mentioned in this post. However, because I'm doing a 4-by-n grid and I'm doing a loop, assigning a name to each subplot seems troublesome to me. Any ideas? Thank you in advance!

Currently my function looks like this:

def make_plots(df, name_list):
    n = len(name_list)
    j = 1
    plt.figure(1, dpi=500, figsize=(10,10/4*n/4))
    for i in name_list:
        plt.subplot(n/4,4,j)
        plt.title('Table {}: {}'.format(j,i), size='xx-small')
        plt.grid(False)
        a = [i for i in list(df[i]) if i>0]
        plt.hist(a,bins=7,rwidth=0.7)
        plt.axvline(x=np.mean(a), color='red')
        j+=1
    plt.tight_layout(pad=0.2,h_pad=0.2, w_pad=0.2)
    plt.show()

Upvotes: 1

Views: 246

Answers (1)

DavidG
DavidG

Reputation: 25363

You could create the figure and subplots first and use the sharey = True argument. Then use zip to iterate over both name_list and the axes array at the same time:

def make_plots(df, name_list):
    n = len(name_list)
    j = 1
    fig, axes = plt.subplots(n/4, 4, sharey=True, figsize=(10, 10/4*n/4))

    for i, ax in zip(name_list, axes.flatten()):

        ax.set_title('Table {}: {}'.format(j,i), size='xx-small')
        ax.grid(False)
        a = [i for i in list(df[i]) if i>0]
        ax.hist(a,bins=7,rwidth=0.7)
        ax.axvline(x=np.mean(a), color='red')
        j+=1
    plt.tight_layout(pad=0.2,h_pad=0.2, w_pad=0.2)
    plt.show()

Upvotes: 1

Related Questions