5

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

我的实际用法是在其上绘制带有 geom_jitter 的箱线图以显示数据分布,我想标记异常点或符合特定条件的点(例如,用于为绘图着色的值的下 10% )。

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

[更新]

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

他要求一个最小的数据集。我刚刚修改了他的示例(标签列中的唯一标识符)

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

这是 joran 示例与我的数据并将 id 的显示降低到最低 1% 的结果 带有抖动点和标签的箱线图在较低的 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)))

带有抖动点和标签的箱线图在较低的 1% 值中

4

2 回答 2

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))        
于 2011-07-01T18:18:19.453 回答
1

只是 Joran 出色解决方案的一个补充:当我尝试使用 facet_wrap() 在多面图中使用时,我遇到了 x 轴定位问题。问题是,ggplot2 使用 1 作为每个方面的 x 值。解决方案是创建一个抖动的 1 向量:

datJit$xj <- jitter(rep(1,length(dat$x)),amount=0.1)
于 2015-12-13T20:42:54.153 回答