2

I am creating multiple categorical plots for data frame df with a for loop:

object_bol = df.dtypes == 'object'
for catplot in df.dtypes[object_bol].index:
    sns.countplot(y=catplot,data=df)

plt.show()

Output is all the plots sequenced one after the other, how do i assign this to a grid with n columns and m rows (n & m vary depending on number of objects in data frame)?

Parfait
  • 104,375
  • 17
  • 94
  • 125
mickeyt500
  • 85
  • 1
  • 5
  • 4
    Do you have sample data? I think you should look at the [FacetGrid](https://seaborn.pydata.org/generated/seaborn.FacetGrid.html). – Scott Boston Aug 18 '17 at 23:05
  • Using the usual `plt.subplots` meachnism is probably fine as well, but without a thorough explanation of the input data and desired outcome this question is probably not answerable. – ImportanceOfBeingErnest Aug 19 '17 at 11:49
  • The input data is a data frame with lets say 20 variables, out of which 15 are categorical, hence filtering them with type objects. The for loop above plots count plots for each of the categorical variable but in a single column. This works for small datasets but datasets with 20+ categorical variable its too tedious to scroll down and i would like those 20+ plots to be arranged in a grid with lets saw 4 columns and 5 rows. Hope that helps understand the question better. – mickeyt500 Aug 19 '17 at 16:44
  • 1
    This is not a comment, instead it should be part of the question. You probably want to read [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well. – ImportanceOfBeingErnest Aug 19 '17 at 18:25

1 Answers1

9

You would want to extend the example from How do I plot two countplot graphs side by side in seaborn? to more subplots.

import numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame(np.random.choice(list("abcd"), size=(100,20), p=[.4,.3,.2,.1]))

fig, axes =plt.subplots(5,4, figsize=(10,10), sharex=True)
axes = axes.flatten()
object_bol = df.dtypes == 'object'
for ax, catplot in zip(axes, df.dtypes[object_bol].index):
    sns.countplot(y=catplot, data=df, ax=ax, order=np.unique(df.values))

plt.tight_layout()  
plt.show()

enter image description here

You would get something similar without seaborn directly from pandas:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame(np.random.choice(list("abcd"), size=(100,20), p=[.4,.3,.2,.1]))

df.apply(pd.value_counts).plot(kind="barh", subplots=True, layout=(4,5), legend=False)

plt.tight_layout()  
plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712