create a line graph using ggplot2 of the change in mean overtime with 95% CI

Viewed 39

My dataset is something like this

df <- data.frame(time = c(0,0,1,1,2,2),
                 mean = c(8, 6, 7 , 6, 6, 5), 
                 Group = c('intervention','control','intervention','control','intervention','control'), 
                 lower = c(7, 5, 5, 4, 4, 4), 
                 upper = c(12, 9, 10, 8, 8, 8))

I want to create a plot of the changes in mean at the 3-time points by group, each of which has the corresponding 95% CI (lower, upper), something like this, the y-axis is mean, and the x-axis is time.

ggplot(df, aes(x = time, y = mean, color = Group)) +
  geom_line(aes(lty = as.character(Group)),
            position = position_dodge(width = 0.1)) +
  geom_errorbar(aes(ymax = upper, ymin = lower), width = 0.1,
                position = position_dodge(width = 0.1)) +
  geom_point(aes(shape = as.character(Group)),
             position = position_dodge(width = 0.1)) +
  guides(lty = "none", shape = "none")+
  theme_classic()

enter image description here

But now, instead of using a continuous variable, I need to change the time variable to a categorical variable

df1 <- data.frame(time = c('baseline','baseline','week 1','week 1','week 2','week 2'),
                 mean = c(8, 6, 7 , 6, 6, 5), 
                 Group = c('intervention','control','intervention','control','intervention','control'), 
                 lower = c(7, 5, 5, 4, 4, 4), 
                 upper = c(12, 9, 10, 8, 8, 8))

and the line disappeared. How can I fix it? enter image description here

1 Answers

Perhaps like this?

ggplot(df, aes(x = time, y = mean, group = group)) +
  geom_line(aes(lty = as.character(group)),
            position = position_dodge(width = 0.1)) +
  geom_errorbar(aes(ymax = upper, ymin = lower), width = 0.1,
                position = position_dodge(width = 0.1)) +
  geom_point(aes(shape = as.character(group)),
             position = position_dodge(width = 0.1)) +
  guides(lty = "none", shape = "none")

enter image description here

Related