Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot multiple histograms with seaborn

I have a data frame with 36 columns. I want to plot histograms for each feature in one go (6x6) using seaborn. Basically reproducing df.hist() but with seaborn. My code below shows the plot for only the first feature and all other come empty.

enter image description here

Test dataframe:

df = pd.DataFrame(np.random.randint(0,100,size=(100, 36)), columns=range(0,36))

My code:

import seaborn as sns
# plot
f, axes = plt.subplots(6, 6, figsize=(20, 20), sharex=True)
for feature in df.columns:
    sns.distplot(df[feature] , color="skyblue", ax=axes[0, 0])
like image 245
aviss Avatar asked Apr 09 '26 03:04

aviss


1 Answers

I guess it would make sense to loop over the axes and features simultaneously.

f, axes = plt.subplots(6, 6, figsize=(20, 20), sharex=True)
for ax, feature in zip(axes.flat, df.columns):
    sns.distplot(df[feature] , color="skyblue", ax=ax)

Numpy arrays are flattened by row-wise, i.e. you would get the first 6 features in the first row, the features 6 to 11 in the second row etc.

If this is not what you want, you can define the index for the axes array manually,

f, axes = plt.subplots(6, 6, figsize=(20, 20), sharex=True)
    for i, feature in enumerate(df.columns):
        sns.distplot(df[feature] , color="skyblue", ax=axes[i%6, i//6])

e.g. the above will fill the subplots column by column.

like image 52
ImportanceOfBeingErnest Avatar answered Apr 10 '26 20:04

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!