以iris资料集为例,我们做一个简单的探索性的数据分析。目的是是为了看到各个变量的分布,以便于我们后面对于一些不平衡的变量进行处理
首先要对数据集包含的内容有一个大致的了解
# 查看这个数据集包含的变数,以及每个变数的数据形态。也可以用str()来查看形态
head(iris)
# 查看类别变数中每个种类的数量
table(iris$Species)
然后我们透过不同的图来来进行更全面分析
- 散点图
# 透过散点图看数据的分布
library(ggplot2)
ggplot(iris,aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point()
# 将每个种类用颜色区分出来,更直观的看出它的分布情况
# 首先要对点图分组,这通过aes(colour = Species)来实现
library(ggplot2)
ggplot(iris,aes(x = Sepal.Length, y = Sepal.Width,colour=Species)) +
geom_point()+
scale_colour_hue()+
theme(legend.position="top")
- 箱型图
# 透过箱型图可以看到各个种类的某一个特征的分布情况
ggplot(iris,aes(x = Species, y = Sepal.Length ,colour=Species)) +
ylim(4,8)+
geom_boxplot()+
scale_colour_hue()+
theme(legend.position="top")
# 通过geom_point函数,向箱线图中添加点,geom_jitter()函数是geom_point(position = "jitter")的包装,binaxis="y"是指沿着y轴进行分箱
ggplot(iris,aes(x = Species, y = Sepal.Length ,colour=Species)) +
ylim(4,8)+
geom_boxplot(width = .5)+
geom_jitter(shape=16, position=position_jitter(.2))+
scale_colour_hue()+
theme(legend.position="top")
- 提琴图
# 提琴图结合了三点图和箱型图的有点,可以更清晰的看出数据分布的特征。
# 数据集中的区域,就会比较胖。数据比较稀疏的区域,就会较瘦
ggplot(iris,aes(x = Species, y = Sepal.Length, fill=Species)) +
ylim(4,8)+
geom_violin(width = .6)+ # 可以调整一下width让图看起来舒服一点
scale_colour_hue()+
theme(legend.position="top")
- 密度分布图
# 透过密度函数可以查看出不同种类的密度分布
ggplot(iris,aes(x = Sepal.Length, fill=Species)) +
geom_density(alpha=.3)+ # 透过alpha来调节透明度
scale_colour_hue()+
theme(legend.position="top")
- 相关矩阵图
# 相关矩阵图可以
library("GGally")
data(iris)
ggscatmat(iris, columns = 1:4,color = 'Species' )
- 调和曲线图
# 调和曲线 Andrews curve,它使用样本的属性作为Fourier级数的系数,然后绘制
library(MSG)
# 这里就是采用数据集irish中的第五个变量的取值来设置颜色(当然这其实也是分类变量可视化的一种很好的办法)
andrews_curve(iris[, -5], col = as.integer(iris[, 5]))
# parallelplot也是高维数据可视化的一种方式
library(lattice)
parallelplot(~iris[1:4],col = as.integer(iris[, 5]))
参考资料: This notebook demos Python data visualizations on the Iris dataset
一个无聊的数据分析公众号,时常有一些脑洞的实例分析。
让我们一起学习,打通各种技能!