adding text to ggplot geom_jitter points that match a condition
如何在使用geom_jittered渲染的点上添加文本以标记它们? geom_text不起作用,因为我不知道抖动点的坐标。您能否捕获抖动点的位置,以便传递给geom_text?
我的实际用法是在上面绘制带有geom_jitter的箱线图以显示数据分布,我想标记离群点或与特定条件匹配的点(例如,将图上色的值的下限为10% )。
一种解决方案是捕获抖动图的xy位置,然后在另一层中使用它,这可能吗?
[更新]
根据Joran的回答,一种解决方案是使用基本包中的抖动函数计算抖动值,将其添加到数据帧中,然后将其与geom_point一起使用。为了进行过滤,他使用ddply来创建一个过滤器列(逻辑向量),并将其用于在geom_text中设置数据子集。
他要求一个最小的数据集。我刚刚修改了他的示例(标签列中的唯一标识符)
1 2 | dat <- data.frame(x=rep(letters[1:3],times=100),y=runif(300), lab=paste('id_',1:300,sep='')) |
这是joran示例使用我的数据并将ID显示降低到最低1%的结果
这是对代码的修改,以使另一个变量具有颜色并显示该变量的某些值(每组最低1%):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | library("ggplot2") #Create some example data dat <- data.frame(x=rep(letters[1:3],times=100),y=runif(300), lab=paste('id_',1:300,sep=''),quality= rnorm(300)) #Create a copy of the data and a jittered version of the x variable datJit <- dat datJit$xj <- jitter(as.numeric(factor(dat$x))) #Create an indicator variable that picks out those # obs that are in lowest 1% by x datJit <- ddply(datJit,.(x),.fun=function(g){ g$grp <- g$y <= quantile(g$y,0.01); g$top_q <- g$qual <= quantile(g$qual,0.01); g}) #Create a boxplot, overlay the jittered points and # label the bottom 1% points ggplot(dat,aes(x=x,y=y)) + geom_boxplot() + geom_point(data=datJit,aes(x=xj,colour=quality)) + geom_text(data=subset(datJit,grp),aes(x=xj,label=lab)) + geom_text(data=subset(datJit,top_q),aes(x=xj,label=sprintf("%0.2f",quality))) |
您的问题尚不完全清楚; 例如,您在一个点上提到了标记点,但同时又提到了着色点,因此我不确定您是真正的意思,还是两者都不 一个可复制的示例将非常有帮助。 但是就我而言,下面的代码做了一些我认为您要描述的事情:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #Create some example data dat <- data.frame(x=rep(letters[1:3],times=100),y=runif(300), lab=rep('label',300)) #Create a copy of the data and a jittered version of the x variable datJit <- dat datJit$xj <- jitter(as.numeric(factor(dat$x))) #Create an indicator variable that picks out those # obs that are in lowest 10% by x datJit <- ddply(datJit,.(x),.fun=function(g){ g$grp <- g$y <= quantile(g$y,0.1); g}) #Create a boxplot, overlay the jittered points and # label the bottom 10% points ggplot(dat,aes(x=x,y=y)) + geom_boxplot() + geom_point(data=datJit,aes(x=xj)) + geom_text(data=subset(datJit,grp),aes(x=xj,label=lab)) |
只是Joran出色解决方案的补充:
当我尝试使用facet_wrap()在多面图中使用时,在x轴定位方面遇到麻烦。 问题在于,ggplot2在每个方面都使用1作为x值。 解决方案是创建一个抖动的1s向量:
1 | datJit$xj <- jitter(rep(1,length(dat$x)),amount=0.1) |