统计转换和位置调整是ggplot2包中的重要概念,统计转换通常使用stat参数来引用,位置调整通常使用position参数来引用。
bin是分箱的意思,在统计学中,数据分箱是一种把多个连续值分割成多个区间的方法,每一个小区间叫做一个bin(bucket),这就意味着每个bin定义一个数值区间,连续值会落到相应的区间中。
一,统计转换图层
使用stat_函数可以减少图层的使用,从而引起对统计变换的注意,而不是视觉外观。
1,移除重复值
使用stat_unique()移除重复值:
stat_unique(mapping = NULL, data = NULL, geom = "point", position = "identity", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE)
参数注释:
- geom:指定几何图层,默认值是point
- position:位置调整,默认值是identity(不做位置调整)
使用unique的两种方式:
ggplot(dat, aes(x, y)) + geom_point(size=5,alpha=0.2,stat = "unique") ggplot(dat, aes(x, y))+stat_unique(geom="point",size=5,alpha=0.2)
2,不改变数据
identity是对数据不做任何改变:
stat_identity(mapping = NULL, data = NULL, geom = "point", position = "identity", ..., show.legend = NA, inherit.aes = TRUE)
使用identity的两种方式:
stat="identity" stat_identity()
3,计数
stat图层中有两种计数方式:
- stat_count() :不需要分箱,计算每个x位置的数量,适用于离散或连续的x轴数据;
- stat_bin():通过把x轴分箱并计算每个箱中的观测数量,适用于连续的x轴数据。
分箱计数转换默认的几何图形是bar,常用于直方图(geom_histogram(stat = "bin")中:
stat_bin(mapping = NULL, data = NULL, geom = "bar", position = "stack", ..., binwidth = NULL, bins = NULL, center = NULL, boundary = NULL, breaks = NULL, closed = c(