2017-06-20 132 views
1

我嘗試在x軸上連接來自兩種不同方法(度量)的測量之間的抖動點。這些測量彼此連接由先證者(一個),可被分成兩個主要的組中,患者(輕拍)和對照(CTR) 我df是這樣的:ggplot:在離散x軸上連接一組內的每個點

set.seed(1) 
a<- rep(paste0("id","_",1:20),each=2) 
value<- sample(1:10,40,rep=TRUE) 
measure<- rep(c("a","b"),20) 
group<- rep(c("pat","ctr"),each=2,10) 
df<-data.frame(a,value,measure,group) 

我試圖

ggplot(df,aes(measure,value,fill=group))+geom_point(position=position_jitterdodge(
     jitter.width=0.1,jitter.height=.1, 
     dodge.width=.75), 
     shape=1)+ 
geom_line(aes(group=a),position=position_dodge(.75)) 

我使用的填充審美爲了將抖動點從兩組分開(輕拍ç tr)。我意識到,當我把這個小組=美學放到ggplot主調用中時,它不會很好地分離,但似乎更好地鏈接到點。 (FIG1 with group aes in ggplot call,圖2 with group aes in geom_line

我的問題:是否有辦法的線條更好地連接到(抖動)點,但保持兩個主要羣體的分離,CTR拍拍

非常感謝。

+0

[這個問題](https://stackoverflow.com/questions/39533456/r-how-to-jitter-both-geom-line-and-geom-point-in- ggplot2-linegraph/39533567#39533567)似乎密切相關。其中一個答案顯示瞭如何手動抖動點。 – aosmith

+0

感謝您的快速回答。不幸的是,這兩個答案都來自這個建議的帖子並不適用於我的問題,因爲兩個答案都不會將這兩行分隔爲兩個主要組(ctr和pat) – Tjebo

+0

[This answer](https://stackoverflow.com/a/37022723/ 2461552)通過「互動」展示了另一種方法。缺點是它會改變你的具體情況。我能想到的唯一的其他選擇是手動遮擋和抖動數據。 – aosmith

回答

2

您遇到的最大的問題是,你只group躲着點,但該行正在a躲閃,也是如此。

要使軸線保持原樣,一種方法是手動閃避數據。這利用了引擎蓋下整數的因素,將group的一個等級向右移動,另一個向左移動。

df = transform(df, dmeasure = ifelse(group == "ctr", 
            as.numeric(measure) - .25, 
            as.numeric(measure) + .25)) 

然後你可以用measure爲x軸的情節,然後使用「迴避」變量爲x軸變量geom_pointgeom_line

ggplot(df, aes(x = measure, y = value)) + 
    geom_blank() + 
    geom_point(aes(x = dmeasure), shape = 1) + 
    geom_line(aes(group = a, x = dmeasure)) 

enter image description here

如果你也想抖動,那也可以手動添加到您的X和Y兩個變量。

df = transform(df, dmeasure = ifelse(group == "ctr", 
            jitter(as.numeric(measure) - .25, .1), 
            jitter(as.numeric(measure) + .25, .1)), 
       jvalue = jitter(value, amount = .1)) 

ggplot(df, aes(x = measure, y = jvalue)) + 
    geom_blank() + 
    geom_point(aes(x = dmeasure), shape = 1) + 
    geom_line(aes(group = a, x = dmeasure)) 

enter image description here

+0

這就是我正在尋找的。乾杯! – Tjebo