ggplot:在离散的x轴上连接一个组内的每个点

时间:2017-06-20 14:47:15

标签: r ggplot2 grouping linegraph jitter

我尝试在x轴上连接来自两种不同方法(测量)的测量之间的抖动点。这些测量结果通过先证者( a )相互关联,可以分为两大类:患者( pat )和对照组( ctr EM>), 我的df是这样的:

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))

我使用填充美学来分离两组中的抖动点( pat ctr )。我意识到,当我将群组= a美学纳入ggplot主要调用时,它并没有很好地分离,但似乎更好地链接到这些点。 (图1 with group aes in ggplot call,图2 with group aes in geom_line

我的问题:有没有办法更好地将线连接到(抖动)点,但保持两个主要组的分离, ctr pat

非常感谢。

1 个答案:

答案 0 :(得分:3)

你遇到的一个重大问题是,你只是group躲避点数,但a也会躲过这些线。

要使您的线与轴保持一致,一个选项是手动躲避您的数据。这利用了引擎盖下的整数因素,将group的一个级别向右移动,另一个级别向左移动。

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

然后你可以用measure作为x轴制作一个情节,然后使用&#34;躲闪&#34;变量为geom_pointgeom_line中的x轴变量。

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