使用 Seaborn 绘制密度图

时间:2021-06-21 23:48:30

标签: python matplotlib seaborn

我有一个包含两个特征的数据集,我使用 Seaborn.relplot 根据另一个绘制它们,得到了这个结果:

Simple scatterplot

但我想使用 Seaborn 添加点密度,正如我们在 this discussionthis one 中观察到的那样,请参见下面的图。

Simple density enter image description here

我如何使用 Seaborn 做到这一点?

1 个答案:

答案 0 :(得分:2)

与您的 second link 一样,但使用 sns.scatterplot 代替:

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

或者,覆盖一个 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

相关问题