r - incorrect grouping in plotting longitudinal data with ggplot -


i trying plot longitudinal dataset ggplot. here example data illustrate problem.

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

here plot got. lines totally screwed. wrong plot? thank you.

enter image description here

you need replace group=1 group=tx:

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


Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -