Search code examples
pythonpandasseabornsubplotdisplot

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


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?


Solution

  • 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)
    })