将文本添加到符合条件的ggplot geom_jitter点

Pab*_*cia 5 r ggplot2 plyr

如何将文本添加到使用geom_jittered渲染的点以标记它们?geom_text不起作用,因为我不知道抖动点的坐标.你能捕捉到抖动点的位置,以便传递给geom_text吗?

我的实际用法是绘制一个带有geom_jitter的boxplot来显示数据分布,我想标记异常点或符合特定条件的那些(例如,用于颜色的值的下限为10%) ).

一种解决方案是捕获抖动图的xy位置,稍后在另一层使用它,这可能吗?

[更新]

从Joran的回答中,解决方案是使用基本包中的抖动函数计算抖动值,将它们添加到数据帧并将其与geom_point一起使用.对于过滤,他使用ddply来获得一个过滤列(逻辑向量)并使用它来对geom_text中的数据进行子集化.

他要求提供最小的数据集.我刚刚修改了他的例子(标签列中的唯一标识符)

dat <- data.frame(x=rep(letters[1:3],times=100),y=runif(300),
                      lab=paste('id_',1:300,sep='')) 
Run Code Online (Sandbox Code Playgroud)

这是我的数据的joran示例的结果,并将ID的显示降低到最低的1% 带有抖动点和标签的boxplot,低1%值

这是对代码的修改,使其具有另一个变量的颜色并显示该变量的一些值(每个组的最低1%):

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)))
Run Code Online (Sandbox Code Playgroud)

带有抖动点和标签的boxplot,低1%值

jor*_*ran 8

你的问题并不完全清楚; 例如,你提到了一点上的标记点,但也提到了着色点,所以我不确定你的意思,或者两者兼而有之.一个可重复的例子将非常有用.但是我使用了一些猜测,下面的代码就是我认为你所描述的:

#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))        
Run Code Online (Sandbox Code Playgroud)