3

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?

FiReTiTi
  • 5,597
  • 12
  • 30
  • 58
  • You can use the method in your second link directly with `sns.scatterplot`. Another option would be to overlay a bivariate kde plot [as in this example](https://seaborn.pydata.org/examples/layered_bivariate_plot.html). – Alex Jun 22 '21 at 06:23
  • Thanks, but they don't use seaborn, just matplotlib. – FiReTiTi Jun 22 '21 at 08:20
  • Seaborn is built on top of matplotlib so you can use matplotlib techniques with plots that seaborn generates. – Alex Jun 22 '21 at 09:00
  • Thanks. In fact. I wanted to know if there was a seaboard built in function to do it. – FiReTiTi Jun 22 '21 at 09:24
  • As far as I can tell you need to provide values to either the `hue` or `c` param as your colour values (from `gaussian_kde`) along with the colormap that you want to use. That _is_ the built-in way to do it. – Alex Jun 22 '21 at 09:38

1 Answers1

7

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

Alex
  • 6,610
  • 3
  • 20
  • 38