簡體   English   中英

將文本添加到匹配條件的 ggplot geom_jitter 點

[英]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% 的結果帶有抖動點和標簽的箱線圖在較低的 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)))

帶有抖動點和標簽的箱線圖在較低的 1% 值中

您的問題並不完全清楚; 例如,您在某一點提到了標記點,但也提到了着色點,所以我不確定您的真正意思是什么,或者兩者兼而有之。 一個可重現的例子將非常有幫助。 但是使用我的一點猜測,下面的代碼做了我認為你正在描述的事情:

#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM