这次我们来看一下使用Python进行更深入的数据可视化分析,使用的包为seaborn。
seaborn包中有一些内置数据集,类似于iris,使用load_dataset可以读取使用。
我们选择Titanic,、tips和iris三个数据集进行示例
import seaborn as sns
iris = sns.load_dataset('iris')
tips = sns.load_dataset('tips')
titanic = sns.load_dataset('Titanic')
先看一眼数据集都长什么样:
iris.head()
tips.head()
titanic.head()
一、分类图
1.分类散点图
最基本的散点图可以使用replot函数绘制
sns.relplot(x = 'total_bill', y = 'tip', hue = 'day', data = tips)
还有两种二维的散点图:Stripplot和Swarmplot
sns.stripplot(x = 'species', y = 'sepal_length', data = iris)
sns.swarmplot(x = 'species', y = 'sepal_length', data = iris)
同时这两个散点图还可以用hue参数来添加一维
sns.stripplot(x = 'day', y = 'total_bill', hue = 'size', data=tips)
2.分类分布图
箱线图是最直观的分类分布图之一,反映了原始数据分布的特征,还可以对多组数据进行比较
箱线图的图形中反映了数据的中位数,四分位数和最值分布情况,最值线外的点为异常值、离群点
sns.boxplot(x = 'species', y = 'sepal_length', data = iris)
同理可以用hue参数添加一维
sns.boxplot(x = 'day', y = 'total_bill', hue = 'size', data=tips)
小提琴图是箱线图和密度图的结合,反映了原始数据的分布形状。粗黑线表示四分数范围,延伸的细线表示95%的置信区间,白点为中位数。
sns.violinplot(x = 'species', y = 'sepal_length', data = iris)
sns.violinplot(x = 'day', y = 'total_bill', hue = 'size', data=tips)
当第三维只有两个值时,可以用split参数拆分小提琴
sns.violinplot(x='day', y='total_bill', hue='sex', split = True, data=tips)
小提琴图也可以和散点图相结合
sns.violinplot(x = 'species', y = 'sepal_length', data = iris)
sns.swarmplot(x = 'species', y = 'sepal_length', data = iris, color = 'w', alpha = 0.5)
3.分类估计图
如果我们更关心各个类别之间的估计关系,我们可以用直方图来表示
sns.barplot(x = 'sex', y = 'survived', data = titanic)
三维情况:
sns.barplot(x = 'sex', y = 'survived', hue = 'pclass', data = titanic)
二、分布图
1.单变量分布
sns.kdeplot(data = tips['total_bill'], shade = True)
分布直方图和分布曲线结合:
sns.displot(iris['sepal_length'], kde = True)
2.双变量分布
密度图+分布曲线图:
sns.jointplot(x = 'total_bill', y = 'tip', kind = 'kde', data = tips)
散点图+直方图
sns.jointplot(x = 'total_bill', y = 'tip', data = tips)
数据集所有变量之间的关系:
sns.pairplot(iris, diag_kind = 'kde')
三、相关性
1.相关性热力图:
corrmat = titanic.corr()
sns.heatmap(corrmat, annot = True, vmax = 1, vmin = 0, xticklabels = True, yticklabels = True, square = True)
各个参数含义:
- annot:是否显示数字
- vmax、vmin:最大值、最小值
- xticklabels、yticklabels:是否显示坐标轴
- square:是否为正方形
2.线性回归
用regplot或lmplot进行画图,得到回归直线和该回归直线95%的置信区间
sns.lmplot(x = 'total_bill', y = 'tip', data = tips)
sns.regplot(x = 'total_bill', y = 'tip', data = tips)