How can I plot a standard deviation ribbon for groups of data on a plot that shows individual data?

Viewed 123

I am plotting individual data points for a group of subjects over multiple trials and for 2 conditions. I'm attempting to plot a shaded area showing the standard deviation for all the data points for each subject for the 2 conditions.

I was successful in plotting the data points for each subject showing the different conditions, and for adding a horizontal line showing the mean across subjects/trials for the 2 conditions. My current plot shows a ribbon for the sd but it shows individual subjects sd rather than horizontal lines showing the overall sd for the condition.

Any help would be appreciated! Here is a reproducible example:

data<-data.frame(condition = rep(c('cond1', 'cond2'), each = 12),
                 subject = rep(rep(c('S1', 'S2', 'S3'), each = 4), 2),
                 trial = rep(1:4, 6),
                  outcome = c(0.2106364, 0.1869099, 0.3228022, 0.3630281, 0.2799749, 0.2554127, 
                              0.4020862, 0.6314061, 0.2145335, 0.2443790, 0.3482223, 0.3462646, 
                              0.3516707, 0.3913449, 0.3493624, 0.3020139, 0.3342762, 0.4562572, 
                              0.3442139, 0.4100149, 0.3715823, 0.4643255, 0.4376337, 0.3504932))
                  
ggplot(data, aes(x = subject, y = outcome, color = condition)) + 
  theme_light(base_size = 4) +
  geom_point(alpha = 0.75) + 
  stat_smooth(aes(group = condition), method = 'lm', formula = y~1, se=F, na.rm = T) +
  stat_summary(aes(group = condition, fill = condition), 
    fun.min = function(x) mean(x) - sd(x), 
    fun.max = function(x) mean(x) + sd(x), 
    geom = "ribbon", alpha = 0.3, na.rm = T, xmin = 0, xmax = Inf)

Current Plot

0 Answers
Related