pythonmatplotlibseaborn

Plot with density using Seaborn


I have a dataset with two features, and I used Seaborn.relplot to draw them one according to the other, and I got this result:

Simple scatterplot

But I would like to add the points density using Seaborn as we can observe in this discussion or this one, see plots below.

Simple density enter image description here

How can I do it using Seaborn?


Solution

  • As in your second link but using sns.scatterplot instead:

    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    from scipy import stats
    
    tips = sns.load_dataset("tips")
    
    values = np.vstack([tips["total_bill"], tips["tip"]])
    kernel = stats.gaussian_kde(values)(values)
    fig, ax = plt.subplots(figsize=(6, 6))
    sns.scatterplot(
        data=tips,
        x="total_bill",
        y="tip",
        c=kernel,
        cmap="viridis",
        ax=ax,
    )
    

    Scatterplot with density colour mapped on points

    Alternatively, overlaying a sns.kdeplot:

    fig, ax = plt.subplots(figsize=(6, 6))
    sns.scatterplot(
        data=tips,
        x="total_bill",
        y="tip",
        color="k",
        ax=ax,
    )
    sns.kdeplot(
        data=tips,
        x="total_bill",
        y="tip",
        levels=5,
        fill=True,
        alpha=0.6,
        cut=2,
        ax=ax,
    )
    

    Scatterplot with overlaid kde plot