geom_area中离散轴的ymin和ymax

时间:2013-05-29 14:31:34

标签: r ggplot2

为了对不同的群体与整个群体进行比较,我试图将人口箱图的人口框添加到情节中。当轴是数字时,可以通过geom_areageom_hline

轻松实现
m <- median(mtcars$mpg)
Q1 <- quantile(as.numeric(mtcars$mpg), c(0.25))
Q3 <- quantile(as.numeric(mtcars$mpg), c(0.75))

ggplot(mtcars, aes(x=cyl, y=mpg))+
geom_rect(aes(xmin = -Inf , xmax = Inf , ymin = Q1 , ymax = Q3  ),fill = "blue", alpha = .002)+
geom_hline(yintercept= m,colour = "white", size=1) + scale_x_discrete(breaks=(factor(mtcars$cyl))) + geom_boxplot(aes(group=cyl))+ coord_flip(xlim=c(3,9)) +
 geom_point() + theme_classic()

enter image description here 使用x轴上的因子xmax=Infxmin=-Inf不起作用(可以预期):

m <- median(esoph$ncases)
Q1 <- quantile(as.numeric(esoph$ncases), c(0.25))
Q3 <- quantile(as.numeric(esoph$ncases), c(0.75))

ggplot(esoph, aes(x=agegp, y=ncases))+
geom_rect(aes(xmin = -Inf , xmax = Inf , ymin = Q1 , ymax = Q3  ),fill = "blue", alpha = .002)+
geom_hline(yintercept= m,colour = "white", size=1)  + geom_boxplot(aes(group=agegp))+ coord_flip() + geom_point() + 
theme_classic()

这可行,但不是我想要的。我想要该区域覆盖整个情节。与第一个图上的颜色相比,该区域的颜色也不同(可能与alpha的行为有关)?

ggplot(esoph, aes(x=agegp, y=ncases))+
geom_rect(aes(xmin = min(agegp) , xmax = max(agegp) , ymin = Q1 , ymax = Q3  ),fill = "blue", alpha = .002)+
geom_hline(yintercept= m,colour = "white", size=1)  + geom_boxplot(aes(group=agegp))+ coord_flip() + geom_point() + 
theme_classic()

解决方案/建议?

1 个答案:

答案 0 :(得分:1)

就像Joran所说,只需将geom_area数据放在aes之外。逻辑因为你没有映射。

m <- median(esoph$ncases)
Q1 <- quantile(as.numeric(esoph$ncases), c(0.25))
Q3 <- quantile(as.numeric(esoph$ncases), c(0.75))

ggplot(esoph, aes(x=agegp, y=ncases))+
geom_rect(xmin = -Inf , xmax = Inf , ymin = Q1 , ymax = Q3  ,fill = "blue", alpha = .002)+
geom_hline(yintercept= m,colour = "white", size=1)  + geom_boxplot(aes(group=agegp))+ coord_flip() + geom_point() + 
theme_classic()

enter image description here