[英]adding text to ggplot geom_jitter points that match a condition
如何将文本添加到使用 geom_jittered 渲染到 label 的点? geom_text 不起作用,因为我不知道抖动点的坐标。 您能否捕获抖动点的 position 以便我可以传递给 geom_text?
我的实际用法是 plot 一个箱线图,上面带有 geom_jitter 以显示数据分布,我想 label 离群点或符合特定条件的点(例如,用于为图着色的值的较低 10% )。
一种解决方案是捕获抖动图的 xy 位置并稍后在另一层中使用它,这可能吗?
根据 Joran 的回答,一种解决方案是使用基础 package 中的抖动 function 计算抖动值,将它们添加到数据帧中并将它们与 geom_point 一起使用。 对于过滤,他使用 ddply 有一个过滤列(一个逻辑向量)并将其用于对 geom_text 中的数据进行子集化。
他要求一个最小的数据集。 我刚刚修改了他的示例(label 列中的唯一标识符)
dat <- data.frame(x=rep(letters[1:3],times=100),y=runif(300),
lab=paste('id_',1:300,sep=''))
这是 joran 示例与我的数据并将 id 的显示降低到最低 1% 的结果
这是对代码的修改,使 colors 由另一个变量显示,并显示该变量的一些值(每组的最低 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)))
您的问题并不完全清楚; 例如,您在某一点提到了标记点,但也提到了着色点,所以我不确定您的真正意思是什么,或者两者兼而有之。 一个可重现的例子将非常有帮助。 但是使用我的一点猜测,下面的代码做了我认为你正在描述的事情:
#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() 在多面 plot 中使用时,我遇到了 x 轴定位问题。 问题是,ggplot2 使用 1 作为每个方面的 x 值。 解决方案是创建一个抖动的 1 向量:
datJit$xj <- jitter(rep(1,length(dat$x)),amount=0.1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.