How to create a figure with subplots for each category in a pandas column

165 Views Asked by At

I have a pandas df which I would like to plot in a displot with seaborn. I have a variable to plot, A, and a variable to hue, B. The problem is that the B variable has ca. 50 different values, so I would like to automatically create a grid of each subplots, say 5 columns and the neccessary number of rows.

Right now I can only put the plots in row or columns, with:

sns.displot(data=df, x="A", col="B")

or

sns.displot(data=df, x="A", row="B")

Is there a way to achieve the desired result?

2

There are 2 best solutions below

1
On BEST ANSWER

Are you looking for col_wrap ?

col_wrap : int
Wrap the column variable at this width, so that the column facets span multiple rows..

g = sns.displot(data=df, x="A", col="B", hue="B", col_wrap=5, height=3, aspect=1)

g.fig.tight_layout()

plt.show();

Output :

enter image description here

Input used :

from string import ascii_uppercase

np.random.seed(1)

df = pd.DataFrame({
    "A": np.random.randn(1000),
    "B": np.random.choice([*list(ascii_uppercase[-10:])], 1000)
})
0
On
# plot the dataframe
ax = df.plot(kind='hist', by='B', bins=20, layout=(2, 5), figsize=(15, 6), legend=False, ec='k', sharey=True, sharex=True)

enter image description here