📜  Seaborn Kdeplot – 综合指南

📅  最后修改于: 2022-05-13 01:55:37.089000             🧑  作者: Mango

Seaborn Kdeplot – 综合指南

核密度估计 (KDE) 图和 Kdeplot 允许我们从一个或多个维度的数据集曲线中估计连续或非参数的概率密度函数,这意味着我们可以为多个样本创建单个图形,这有助于更多高效的数据可视化。

为了使用 Seaborn 模块,我们需要使用以下命令安装该模块:

pip install seaborn

我们通过一些具体的例子来学习一些参数的用法:

首先导入对应的库

Python3
import pandas as pd
import seaborn as sb
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline


Python3
# data x and y axis for seaborn
x= np.random.randn(200)
y = np.random.randn(200)
  
# Kde for x var
sns.kdeplot(x)


Python3
sns.kdeplot(y)


Python3
sns.kdeplot(x, shade = True)


Python3
sns.kdeplot(x, shade = True , color = "Green")


Python3
sns.kdeplot(x, vertical = True)


Python3
sns.kdeplot(x,y)


Python3
sns.kdeplot(x,y, shade = True)


Python3
sns.kdeplot(x,y, cmap = "winter_r")


Python3
sns.kdeplot(x, y, shade=True, cbar=True)


Python3
iris = sns.load_dataset('iris')
iris


Python3
setosa = iris.loc[iris.species=="setosa"]
virginica = iris.loc[iris.species == "virginica"]
sns.kdeplot(setosa.petal_length, setosa.petal_width)


Python3
sns.kdeplot(setosa.sepal_width, setosa.sepal_length)


Python3
sns.kdeplot(setosa.petal_length, setosa.petal_width)
sns.kdeplot(virginica.petal_length, virginica.petal_width)


绘制一个简单的一维kde图像:

让我们看看变量 x 轴和 y 轴的 Kde,所以让 x 变量传递给 kdeplot() 方法。

蟒蛇3

# data x and y axis for seaborn
x= np.random.randn(200)
y = np.random.randn(200)
  
# Kde for x var
sns.kdeplot(x)

输出:

然后在检查y轴之后。

蟒蛇3

sns.kdeplot(y)

输出:

使用 Shade 填充曲线覆盖的区域:

我们可以使用阴影突出显示曲线覆盖的区域。如果为True,则在kde曲线下方区域进行阴影处理,颜色控制曲线和阴影的颜色

蟒蛇3

sns.kdeplot(x, shade = True)

输出:

您可以使用颜色属性更改阴影颜色:

蟒蛇3

sns.kdeplot(x, shade = True , color = "Green")

输出:

使用 Vertical to draw 指示是在 X 轴上绘制还是在 Y 轴上绘制

蟒蛇3

sns.kdeplot(x, vertical = True)

输出:

两个变量的双变量 Kdeplot:

简单地将两个变量传递给 seaborn.kdeplot() 方法。

蟒蛇3

sns.kdeplot(x,y)

输出:

使用阴影属性对曲线覆盖的区域进行着色:

蟒蛇3

sns.kdeplot(x,y, shade = True)

输出:

现在您可以使用cmap属性更改颜色:

蟒蛇3

sns.kdeplot(x,y, cmap = "winter_r")

输出:

Cbar 的使用:如果为 True,则添加颜色条以注释双变量图中的颜色映射。注意:目前不支持带有色调变量的图。

蟒蛇3

sns.kdeplot(x, y, shade=True, cbar=True)

输出:

让我们看看 Iris 数据集的例子,它是宽格式数据集每一列的分布图:

Iris 数据集包含 3 种不同类型的鸢尾花(Setosa、Versicolour 和 Virginica)花瓣和萼片长度,存储在 150×4 numpy.ndarray 中

为 Kdeplot 加载 iris 数据集:

蟒蛇3

iris = sns.load_dataset('iris')
iris

输出:

iris 两个变量的双变量 Kdeplot:

一旦我们设置了物种,那么如果我们想简单地计算 petal_length 和 petal_width 那么简单地将两个变量(Setosa 和 verginica )传递给 seaborn.kdeplot() 方法。

蟒蛇3

setosa = iris.loc[iris.species=="setosa"]
virginica = iris.loc[iris.species == "virginica"]
sns.kdeplot(setosa.petal_length, setosa.petal_width)

输出:

如果我们要计算另一个变量属性 sepal_width 和 sepal_length,请参见另一个示例。

蟒蛇3

sns.kdeplot(setosa.sepal_width, setosa.sepal_length)

输出:

如果我们使用不同的变量传递两个单独的 Kdeplot:

蟒蛇3

sns.kdeplot(setosa.petal_length, setosa.petal_width)
sns.kdeplot(virginica.petal_length, virginica.petal_width)

输出: