How can I add a confidence interval to this violin plot?
df <- data.frame("Need" = c(3,4.3,4.5,2.2,5.1,5.2), "Condition" = c("A","A","A","B","B","B"))
ggplot(df,aes(x = Condition, y = Need, fill=Condition)) +
geom_violin() +
stat_summary(fun.data = "mean_cl_boot", geom = "pointrange",
colour = "red") +
ggtitle("Needs by condition violin plot"))
I can't attach pictures yet, but you get the gist. With this code I can create violin plots with standard deviation lines for each violin plot, but I'd add 95% confidence interval lines.
Any ideas?
What you can do is first calculate the error bars per condition and after that add them by using geom_errorbar
like this:
library(tidyverse)
stats <- df %>%
group_by(Condition) %>%
summarise(Mean = mean(Need), SD = sd(Need),
CI_L = Mean - (SD * 1.96)/sqrt(6),
CI_U = Mean + (SD * 1.96)/sqrt(6))
ggplot() +
geom_violin(df, mapping = aes(x = Condition, y = Need, fill=Condition)) +
stat_summary(fun.data = "mean_cl_boot", geom = "pointrange",
colour = "red") +
geom_point(stats, mapping = aes(Condition, Mean)) +
geom_errorbar(stats, mapping = aes(x = Condition, ymin = CI_L, ymax = CI_U), width = 0.2) +
ggtitle("Needs by condition violin plot")
Output: