导入鸢尾花数据集
from __future__ import division
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid", color_codes=True)
iris = pd.read_csv("Iris.csv")
iris.head()
导入结果
绘制相关密度图
types = iris.dropna(subset=['Sepal.Width'])
Alltypes_num = types['Species'].value_counts()
from pylab import *
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
#支持中文
mpl.rcParams['font.sans-serif'] = ['SimHei']
types = list(Alltypes_num[Alltypes_num.values > 4].index)
from IPython.core.pylabtools import figsize
# 类别分数分布图
figsize(12, 10)
# 绘制每个类别
for b_type in types:
# 选择花的类型
subset = iris[iris['Species'] == b_type]
# 各类长度得分的密度图
sns.kdeplot(subset['Sepal.Width'].dropna(), label=b_type, shade=False, alpha=0.8)
sns.kdeplot(subset['Sepal.Length'].dropna(), label=b_type, shade=False, alpha=0.8)
sns.kdeplot(subset['Petal.Length'].dropna(), label=b_type, shade=False, alpha=0.8)
sns.kdeplot(subset['Petal.Width'].dropna(), label=b_type, shade=False, alpha=0.8)
plt.xlabel('Len', size=20)
plt.ylabel('Density', size=20)
plt.legend()
plt.title('鸢尾花总体密度图', size=28)
绘制对偶图
# 提取要绘制的列
plot_data = iris[[
'Sepal.Length', 'Sepal.Width', 'Petal.Length',
'Petal.Width'
]]
# 把 inf 换成 nan
plot_data = plot_data.replace({np.inf: np.nan, -np.inf: np.nan})
# 重命名
plot_data = plot_data.rename(
columns={
'Sepal.Length': '花瓣长度',
'Sepal.Width': '花瓣宽度',
'Petal.Length': '花萼长度',
'Petal.Width': '花萼宽度',
})
# 删除 na 值
plot_data = plot_data.dropna()
# 计算某两列之间的相关系数
def corr_func(x, y, **kwargs):
r = np.corrcoef(x, y)[0][1]
ax = plt.gca()
ax.annotate("r = {:.2f}".format(r),
xy=(.2, .8),
xycoords=ax.transAxes,
size=20)
# 创建 pairgrid 对象
grid = sns.PairGrid(data=plot_data, size=3)
# 上三角是散点图
grid.map_upper(plt.scatter, color='red', alpha=0.6)
# 对角线是直方图
grid.map_diag(plt.hist, color='red', edgecolor='black')
# 下三角是相关系数和二维核密度图
grid.map_lower(corr_func)
grid.map_lower(sns.kdeplot, cmap=plt.cm.Reds)
plt.suptitle('鸢尾花对偶图', size=36, y=1.02)