1

I would like my code to iterate through columns to make one plot for each column. I have the below code to draw plot for one column, but I do not know how to use this code to loop through other columns and generate plots for all columns. Any idea?

Here's my code:

import seaborn as sns

sns.set()
fig, ax = plt.subplots()
sns.set(style="ticks")
sns.boxplot(x='Location', y='Height [cm]', data=df) 
sns.despine(offset=10, trim=True) 
fig.set_size_inches(22,14)
plt.savefig('Height.pdf', bbox_inches='tight') 

This is what my data looks like:

Location            Height          Length       Width    
A                    150             95           18
A                    148             122          25
A                    162             127          16
B                    155             146          32
B                    148             112          21
B                    154             108          30
C                    160             127          22
C                    148             138          36
C                    159             142          28

2 Answers 2

5

Simply putting your code inside a loop and changing the column name and plot name each time should do it (from a quick test it worked for me and I have 3 PDFs saved in my working directory):

import matplotlib.pyplot as plt
import seaborn as sns

for column in df.columns[1:]:  # Loop over all columns except 'Location'
    sns.set()
    fig, ax = plt.subplots()
    sns.set(style="ticks")
    sns.boxplot(x='Location', y=column, data=df)  # column is chosen here
    sns.despine(offset=10, trim=True) 
    fig.set_size_inches(22,14)
    plt.savefig('{}.pdf'.format(column), bbox_inches='tight')  # filename chosen here
Sign up to request clarification or add additional context in comments.

Comments

1

To plot only a specific list of columns Make a list of columns that you want to plot then iterate over the list Here I am plotting a regression plot , Length vs Height and Width vs Height, In a loop .

import matplotlib.pyplot as plt

import seaborn as sns
lst = [ "Length"  , "Width" ]
for i in lst:
    sns.lmplot(x = 'Height', y = i , data = df ) # df is your dataframe 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.