aviss
aviss

Reputation: 2449

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])

Upvotes: 2

Views: 12414

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339630

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.

Upvotes: 11

Related Questions