1. 连续型x能否使用箱型图
1.1 round_any()
#library(plyr)
> head(diamonds$carat,10)
[1] 0.23 0.21 0.23 0.29 0.31 0.24 0.24 0.26 0.22 0.23
> head(round_any(diamonds$carat, 0.1, floor),10)
[1] 0.2 0.2 0.2 0.2 0.3 0.2 0.2 0.2 0.2 0.2
#在0.1的倍数中,找一个k使得恰好0.1k<=i<=0.1(k+1),floor表示用左端值作为近似值
> head(round_any(diamonds$carat, 0.1, ceiling),10)
[1] 0.3 0.3 0.3 0.3 0.4 0.3 0.3 0.3 0.3 0.3
#在0.1的倍数中,找一个k使得恰好0.1k<=i<=0.1(k+1),ceiling表示用右端值作为近似值
diamonds%>%ggplot(aes(carat,depth))+geom_boxplot(aes(group=round_any(diamonds$carat, 0.5, floor)))

1.2 两个问题
1.尽管上面命令中round_any()会返回很多值,但实际只分了不到10组,所以需要想想group接收的是值的数量还是值的unique数?(后者)
2.前些天,有个同学问我一个箱线图的画法,当时他的x轴也是连续型的,我首先想到的是as.factor转一下类型,好在他的x值不多只有三十个,因此看上去问题不大,现在想想,如果x很多成百上千个,比如这里的carat,最好就不要用as.factor了,太紧凑了
diamonds%>%ggplot(aes(as.factor(carat),depth))+geom_boxplot()

1.3 正确认识箱线图

上限:上四分位数+(上四分位数-下四分位数)*1.5
下限:下四分位数-(上四分位数-下四分位数)*1.5
有时候,如果一组数据的最大值(或除去异常值后的最大值)在理论上限值以下,仍以这个最大值画横线。
2. 面积图和密度图在表示数据分布时的异同
1.都是stat="bin"
geom_density默认就是stat="bin"; geom_area默认不是,需要额外指定
2.geom_density, geom_area的position都可以分为"dodge", "fill","stack"。前者默认是"dodge", 后者默认是"stack"
diamonds%>%ggplot(aes(depth))+geom_density(aes(fill=cut,color=cut))
diamonds%>%ggplot(aes(depth))+geom_area(aes(y=..density..,fill=cut),stat="bin",position = "dodge")


网友评论