0

I wrote a code that generates multiple swarm and box plots from a dataframe using a for loop. When I run this in a Jupyter Notebook using python3, each figure is generated separately. Thus, I have to save each one individually. Is there a way where each figure can be saved into one pdf file? As of right now, I have to click on each image and save them individually. If I could also save them in a panel (2 or 3 figures in a row), I would be ecstatic.

Here is my code:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np 

# Random dataframe 
np.random.seed(42)
df = pd.DataFrame(np.random.randint(0,100, size=(6,4)), columns=list('ABCD'))
Groups = ['Group1','Group1', 'Group1', 'Group2', 'Group2', 'Group2'] 
df['Groups'] = Groups
first_column = df.pop('Groups')
df.insert(0, 'Groups', first_column)
col_ids = list(df.columns)
col_ids.remove('Groups')

for col in col_ids: 
fig = plt.figure()
sns.set(style="darkgrid")
ax = sns.boxplot(x='Groups', y=df[col], data=df
ax = sns.swarmplot(x='Groups', y=df[col], data=df, color="grey")
plt.show()


Your answer was very helpful. However, is there a way to change the dimensions of the figure? The boxplots are getting squeezed. I tried 
to add

plt.figure(figsize=(8,11)) plt.show()

to make the image bigger but it gives me the same squished figure. 


[enter image description here][1]


  [1]: https://i.stack.imgur.com/w9mzz.png

1 Answers1

0

If you would like to save them together in a panel, replace the for-loop with the following:

fig, axs = plt.subplots(len(col_ids), 1)
sns.set(style="darkgrid")

for i in range(len(col_ids)): 
    sns.boxplot(x='Groups', y=df[col_ids[i]], data=df, ax=axs[i])
    sns.swarmplot(x='Groups', y=df[col_ids[i]], data=df, color="grey", ax=axs[i])

plt.show()

After that you should be able to save them to one PDF.

emmacb
  • 99
  • 6