2017-07-25 72 views
0

我試圖用ggplot繪製我的縱向數據集。 下面是示例數據來說明我的問題。使用ggplot繪製縱向數據不正確的分組

library(MASS) 
library(ggplot2) 
library(dplyr) 

# create data  
dat.tx.a <- mvrnorm(n=250, mu=c(30, 20, 28), 
         Sigma=matrix(c(25.0, 17.5, 12.3, 
             17.5, 25.0, 17.5, 
             12.3, 17.5, 25.0), nrow=3, byrow=TRUE)) 
    dat.tx.b <- mvrnorm(n=250, mu=c(30, 20, 22), 
         Sigma=matrix(c(25.0, 17.5, 12.3, 
             17.5, 25.0, 17.5, 
             12.3, 17.5, 25.0), nrow=3, byrow=TRUE)) 
    dat <- data.frame(rbind(dat.tx.a, dat.tx.b)) 
    names(dat) = c("measure.1", "measure.2", "measure.3") 
    dat <- data.frame(subject.id=factor(1:500), tx=rep(c("A", "B"), each=250), dat) 
    rm(dat.tx.a, dat.tx.b) 
    dat <- reshape(dat, varying=c("measure.1", "measure.2", "measure.3"), 
        idvar="subject.id", direction="long") 
#ggplot 
dat %>% 
     group_by(tx,time) %>% 
     summarize(mean=mean(measure), sd=sd(measure)) %>% 
     ggplot(aes(x=time, y=mean, color=tx))+ 
     geom_point()+ 
     geom_line(aes(group=1))+ 
     labs(x='Time', y='Cytokine Level') 

這是我得到的情節。線完全擰緊。情節出了什麼問題?謝謝。

enter image description here

+0

'組= 1'告訴ggplot一切在一組連接在一起。刪除它。 – Gregor

回答

0

您需要通過group=tx更換group=1

dat %>% 
    group_by(tx,time) %>% 
    summarize(mean=mean(measure), sd=sd(measure)) %>% 
    ggplot(aes(x=time, y=mean, color=tx))+ 
    geom_point()+ 
    geom_line(aes(group=tx))+ 
    labs(x='Time', y='Cytokine Level') 

enter image description here