[seaborn] seaborn学习笔记4-核密度图DENSITYPLOT

2023-02-14,,

文章目录

4 核密度图Densityplot
1. 基础核密度图绘制 Basic density plot
2. 核密度图的区间控制 Control bandwidth of density plot
3. 多个变量的核密度图绘制 Density plot of several variables
4. 边际核密度图 Marginal Density plot

4 核密度图Densityplot

(代码下载)
核密度图显示数值变量的分布。它只需要一组数值作为输入。它非常类似于直方图。在seaborn中使用kdeplot函数绘制核密度图,该章节主要内容有:

    基础核密度图绘制 Basic density plot
    核密度图的区间控制 Control bandwidth of density plot
    多个变量的核密度图绘制 Density plot of several variables
    边际核密度图 Marginal Density plot
#调用seaborn
import seaborn as sns
#调用seaborn自带数据集
df = sns.load_dataset('iris')
#显示数据集
df.head()
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa

1. 基础核密度图绘制 Basic density plot

基础核密度图函数 default density function
带阴影的核密度图 Density plot with shade
水平核密度图 Horizontal density plot

# 基础核密度图函数 default density function
# 纵坐标为核密度估计值,类似概率密度函数。
# 如x=3.0,纵坐标表示的不是x=3.0处的概率,而是在x=3.0附近取值的可能性估计
sns.kdeplot(df['sepal_width']);
C:\ProgramData\Anaconda3\lib\site-packages\scipy\stats\stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval

# 带阴影的核密度图 Density plot with shade
# density plot with shade 添加阴影线
sns.kdeplot(df['sepal_width'], shade=True);

# 水平核密度图 Horizontal density plot
# 基本所有seaborn绘图函数只要设置vercical就能获得水平方向的图像
sns.kdeplot(df['sepal_width'], shade=True, vertical=True, color="skyblue");

2. 核密度图的区间控制 Control bandwidth of density plot

# bw参数控制核密度图的区间
# 其中bw表示根据多少区间范围来计算核密度
# Large bandwidth
sns.kdeplot(df['sepal_width'], shade=True, bw=.5, color="olive");

 # Narrower bandwidth
sns.kdeplot(df['sepal_width'], shade=True, bw=.05, color="olive");

3. 多个变量的核密度图绘制 Density plot of several variables

# 有时需要比较多个变量的核密度,可以通过matplotlib创建两个子图,也可以直接画在一张图上
p1=sns.kdeplot(df['sepal_width'], shade=True, color="r")
p1=sns.kdeplot(df['sepal_length'], shade=True, color="b")

4. 边际核密度图 Marginal Density plot

# 边际图能够更好变现2个数值变量之间的关系
# No space 无间隔,space表示边缘图和中央图像的间隔,kind表示图像类型
sns.jointplot(x=df["sepal_length"], y=df["sepal_width"], kind='kde', color="grey", space=0);

# Huge space 大间隔
sns.jointplot(x=df["sepal_length"], y=df["sepal_width"], kind='kde', space=3);

# Make marginal bigger, ratio表示中央图像和边缘图的比例,ratio越大,比例越大
sns.jointplot(x=df["sepal_length"], y=df["sepal_width"], kind='kde',ratio=1);

sns.jointplot(x=df["sepal_length"], y=df["sepal_width"], kind='kde',ratio=10);

[seaborn] seaborn学习笔记4-核密度图DENSITYPLOT的相关教程结束。

《[seaborn] seaborn学习笔记4-核密度图DENSITYPLOT.doc》

下载本文的Word格式文档,以方便收藏与打印。