2017-06-20 131 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