Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 954
FiReTiTi Avatar asked Jul 27 '26 06:07

FiReTiTi


1 Answers

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

like image 167
Alex Avatar answered Jul 28 '26 20:07

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!