2

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])
2
  • 3
    ax=axes[0, 0] means that you plot always to the first axes. This is what you observe as well. Maybe you want to plot to different axes? Commented Nov 6, 2018 at 12:02
  • 1
    Oh, that's true. How should I change it? Commented Nov 6, 2018 at 12:04

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.