Gabriela Catalina
Gabriela Catalina

Reputation: 161

Creating Matplotlib subplot using a loop that iterates columns from different Pandas Dataframes

Ok, so I've been trying to fix this since yesterday and can't find a solution.

I created 12 pandas Dataframes (named exp_1 - exp_12) for the data of 12 different experiments, the column names are identical in all of the Dataframes. I want to create a plot with 12 subplots (12x4) with 4 plots per row for every experiment.

So far, so good. Plotting works just fine, I am currently using this code (I shortened it to 4 plots here):

fig, axs = plt.subplots(nrows = 12, ncols=4, figsize = (15,27))
sns.regplot('MecA_SP', 'MecA_MP', data=exp_3, color ='blue', ax=axs[0,0])
sns.regplot('blaOXA_SP', 'blaOXA_MP', color ='lime', data=exp_3, 
ax=axs[0,1])
sns.regplot('Aph3_SP', 'Aph3_MP', data=exp_3, color = 'deeppink', 
ax=axs[0,2])
sns.boxplot(data=exp_3, orient ='h', color ='darkviolet', ax=axs[0,3])
fig.tight_layout()
plt.show()

But I'm trying to create these subplot by using a loop so that I don't have to manually input each the sample names for each and every Dataframe. Right now this is what I have:

 fig, axs = plt.subplots(nrows = 12, ncols=4, figsize = (14,5))
exps = {0: 'exp_1',1: 'exp_2',2: 'exp_3',3: 'exp_4',4: 'exp_5',5: 'exp_6', 
6:'exp_7',7: 'exp_8', 8:'exp_9',9: 'exp_10',10: 'exp_11',11: 'exp_12'}
for x in exps :
    sns.regplot('MecA_SP', 'MecA_MP', data=x, color ='blue', ax=axs[exps[x], 
    0])
    sns.regplot('blaOXA_SP', 'blaOXA_MP', color ='lime', data=x, 
    ax=axs[exps[x], 1])
    sns.regplot('Aph3_SP', 'Aph3_MP', data=x, color = 'deeppink', 
    ax=axs[exps[x], 2])
    sns.boxplot(data=x, orient ='h', color ='darkviolet', ax=axs[exps[x],3])
fig.tight_layout()
plt.show()

This is what I what my plot looks like if I don't use a loop, but just Write the whole thing by hand: enter image description here

Does anyone have an idea how I could solve this? I'll be happy about any suggestions, so thanks in advance

Upvotes: 1

Views: 2314

Answers (1)

Parfait
Parfait

Reputation: 107567

Simply save your dataframes in a list not a dictionary of dataframe names and then iterate to create subplots. Even use enumerate to get a loop count for plot ax position.

exps = [exp_1, exp_2, exp_3, exp_4, exp_5, exp_6
        exp_7, exp_8, exp_9, exp_10, exp_11, exp_12]

fig, axs = plt.subplots(nrows = 12, ncols=4, figsize = (14,5))

for i, x in enumerate(exps):
    sns.regplot('MecA_SP', 'MecA_MP', data=x, color='blue', ax=axs[i, 0])
    sns.regplot('blaOXA_SP', 'blaOXA_MP', data=x, color='lime', ax=axs[i, 1])
    sns.regplot('Aph3_SP', 'Aph3_MP', data=x, color='deeppink', ax=axs[i, 2])
    sns.boxplot(orient='h', data=x, color='darkviolet', ax=axs[i, 3])

fig.tight_layout()
plt.show()
plt.clf()
plt.close()

Upvotes: 2

Related Questions