如何获得'sns.kdeplot'和手动生成的KDE进行匹配?

2024-09-28 01:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在使用sns.kdeplot生成填充的KDE。为了更好地理解引擎盖下发生的事情,我决定尝试自己估算KDE并使用plt.contourf绘制KDE,使用我在this question的答案中找到的代码。然而,我使用这两种方法得到的结果看起来完全不同。我试图确保我的KDE估计实现与Seaborn中的方式相匹配,但我没有发现任何差异。有人能帮我理解为什么我的情节看起来不一样吗

下面是一些示例代码:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

geyser = sns.load_dataset("geyser")

dur = np.array(geyser["duration"])
wait = np.array(geyser["waiting"])

# plot the KDE using sns.kdeplot
sns.kdeplot(dur, wait, shade=True, cmap="binary", cut=0)

# calculate my own KDE and plot using plt.contourf
def make_kde(x, y):
    """
    Based on
    https://stackoverflow.com/questions/50917216/log-scales-with-seaborn-kdeplot
    """
    kde = stats.gaussian_kde([x, y])
    
    xx, yy = np.mgrid[min(x):max(x):(max(x)-min(x))/200,
                      min(y):max(y):(max(y)-min(y))/200]
    
    
    
    density = kde(np.c_[xx.flat, yy.flat].T).reshape(xx.shape)
    
    return xx, yy, density

xgrid, ygrid, density = make_kde(dur, wait)

fig, ax = plt.subplots()
ax.contourf(xgrid, ygrid, density, cmap="binary", levels=10)

以下是由sns.kdeplot生成的绘图:

enter image description here

下面是由plt.contourf生成的图:

enter image description here

我真的很想知道为什么这两个情节看起来不同


Tags: importasnppltmindensitymaxxx

热门问题