How to plot the boxplot of the columns in one loop?

Viewed 1573

I have the following columns in a data-frame df:

columns = ['temperature','humidity' ,'pressure','rain' ,'lightavgw/o0' ,'lightmax','moisture']

What I want is to create a loop where I can plot the boxplot of all the columns through a single loop. I tried the following code:

columns = ['temperature','humidity' ,'pressure','rain' ,'lightavgw/o0' ,'lightmax','moisture']
for col in columns:
    plt.boxplot(df[col])

But its plotting it in the same boxplot. enter image description here

2 Answers

You can directly plot the data frame instead of going through the loop

Example code:

import numpy as np; 
import pandas as pd
import matplotlib.pyplot as plt
data = np.random.random(size=(4,4))
df = pd.DataFrame(data, columns = ['A','B','C','D'])

df.boxplot()
plt.show()

Output:

enter image description here

To plot the figure for each column, use plt.figure() inside the loop

columns = ['temperature','humidity' ,'pressure','rain' ,'lightavgw/o0','lightmax','moisture']
for col in columns:
    plt.figure()   # plots figure for each iteration
    plt.boxplot(df[col])
Related