plot TOTAL errorbar for multiple lines in ggplot r

Viewed 80

I would like to plot the data by subject but adding the errorbar of the total mean and se. I mean, not an error bar for each subject. I've tried geom_errorbar and stat_summary but still failed to get my ideal plot (see the figure I drew). enter image description here

and here is the code I used to draw this figure (the errorbars are added by hand).

ggplot(ASD, aes(x=period, y=meanF0, group=subject, color=group)) + 
      geom_line(aes(color=group, size=group)) +
      scale_size_manual(values=c(.6, .6, .6, .6)) +
      theme_light()+
      xlab("Period")+
      ylab("F0 (Hz)")+
      ggtitle("Mean F0 Adjustment (ASD Group)") +
      geom_point()+
      scale_color_manual(values=c("red")) +
      theme(plot.title = element_text(size=14.5, face="bold", hjust = 0.5,  family = "serif"), 
            axis.title.y= element_text(size=12, face = "bold", family = "serif"),
            axis.title.x= element_text(size=12, face = "bold", family = "serif"),
            axis.text.x = element_text(size=11, face="bold", family = "serif"),
            axis.text.y = element_text(size=11, face="bold", family = "serif"))+
      theme(legend.position = "none")+
      geom_hline(yintercept=112.8, linetype="dashed", 
                 color = "dark grey", size=.7)

Anyone could help? Thank you very much!!!

1 Answers

Use annotate to add the error bars. I don't have your data, so I created my own. You're going to need the confidence interval and the average for each group. My average-by-group values and confidence interval-by-group are stored in df4$meanV and df4$ci. You can replace these with your variable names. In annotate, you'll include the data frame in the call like you would in base R plots. Like base R, you can just use raw values, as well. Multiple values can be joined with c(). As in y = c(12, 10). If you have any questions, just let me know.

ggplot(df2, aes(x = condition, y = value, 
                color = subject, group = subject)) +
  geom_line() + geom_point() + 
  annotate("errorbar",
           x = df4$condition
           ymin = df4$meanV - df4$ci,
           ymax = df4$meanV + df4$ci,
           width = .2) +
  annotate("point",
          x = df4$condition,
          y = df4$meanV) + 
  ylim(min(df2$value), max(df2$value))

enter image description here

Related