1、加载数据
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
import warnings# 禁用所有警告信息
warnings.filterwarnings('ignore')# 加载数据
iris = load_iris()
iris
iris.keys()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['target'] = iris.target
df.head()
2、基于matplotlib的密度图
from scipy.stats import gaussian_kde# 根据数据集构造密度函数
density = gaussian_kde(df['sepal width (cm)'])
density.covariance_factor = lambda : .25
density._compute_covariance()# 构造向量作为x轴刻度
xs = np.linspace(1.5, 5, 200)# 初始化
plt.figure(figsize=(8, 6))plt.plot(xs, density(xs))
plt.show()
3、基于seaborn的密度图
import seaborn as sns
import matplotlib.pyplot as pltsns.set(font='SimHei', font_scale=0.8, style="darkgrid") # 解决Seaborn中文显示问题# 构造子图
fig, ax = plt.subplots(2,2,constrained_layout=True, figsize=(12, 8))# 密度图
ax_sub = sns.kdeplot(df['sepal width (cm)'], ax=ax[0][0])
ax_sub.set_title('密度图')# 水平密度图
ax_sub = sns.kdeplot(y=df['sepal width (cm)'], color="skyblue", ax=ax[0][1])
ax_sub.set_title('水平密度图')# 增加阴影
ax_sub = sns.kdeplot(df['sepal width (cm)'], fill=True, ax=ax[1][0])
ax_sub.set_title('增加阴影')sns.kdeplot(data=df, x='sepal width (cm)', fill=True, bw_method=0.1, ax=ax[1][1]).set_title('降低带宽')plt.show()
4、一图绘制多个变量
ax_sunb = sns.kdeplot(data=df, x='sepal width (cm)', fill=True, color='r', label='sepal width (cm)')
ax_sub = sns.kdeplot(df['sepal length (cm)'], fill=True, color="b", label='sepal length (cm)')
plt.legend()
# 修改x标签
plt.xlabel('speal width/speal length')plt.show()
# alpha:修改透明度
sns.kdeplot(data=df, x='sepal width (cm)', hue="target", fill=True, common_norm=False, alpha=0.4)
# 绘制网格(共用坐标轴)
g = sns.FacetGrid(data=df, col='target', hue='target', col_wrap=3)
# 绘制密度图
g = g.map(sns.kdeplot,"sepal width (cm)", cut=0, fill=True, common_norm=False, alpha=1, legend=False)
# 每个网格的标题
g = g.set_titles("{col_name}")plt.show()
# 绘制堆积图
sns.kdeplot(data=df, x='sepal width (cm)', hue='target', common_norm=False, multiple="fill", alpha=1)plt.show()