I have a large dataset, where I have a variable Q1with 7 response/value options, and two groups (One and Two).
Q1<- c(6,4,2,4,7,1,4,7,4,5,4,4,2,6,1)
Group<- c(One, Two, One, Two,Two, Two, One, One, One, One, Two, One, One, Two, Two)
I'm trying to convert a simple frequency plot (number of observations in each response category by group) and instead plot the means with confidence intervals (as in the image below).

df1<- filter(df, Q1!="-99",df$Group=="One"|df$Group=="Two")
ggplot(data = df1, aes(x = Q1)) +
geom_bar(aes(fill = df1$Group), position = "dodge", stat="summary", fun.y="mean") + labs(title="Graph Title")
When i run this, I get the following error:
Error: stat_summary requires the following missing aesthetics: y
Any ideas are appreciated!
Here is an example. You need to pre-compute CIs yourself:
library(dplyr)
library(ggplot2)
set.seed(123)
df <- data.frame(g = c(rep("A",10),rep("B",10),rep("C",10)),
val = c(rnorm(10,100,5), rnorm(10,200,10), rnorm(10,300,50)))
df <- df %>% group_by(g) %>% summarise(m = mean(val),
stdv = sd(val))
ggplot(df, aes(g,m,fill=g)) +
geom_bar(stat="identity", color="black",
position=position_dodge()) +
geom_errorbar(aes(ymin=m-stdv, ymax=m+stdv), width=.2,
position=position_dodge(.9))
Output

UPDATE
df <- data.frame(
Q1 = c(6,4,2,4,7,1,4,7,4,5,4,4,2,6,1),
Group = sample(c("One","Two"), 15, TRUE),
stringsAsFactors = FALSE)
df <- df %>% group_by(Group) %>% summarise(m = mean(Q1),
stdv = sd(Q1))
ggplot(df, aes(Group,m,fill=Group)) +
geom_bar(stat="identity", color="black",
position=position_dodge()) +
geom_errorbar(aes(ymin=m-stdv, ymax=m+stdv), width=.2,
position=position_dodge(.9))
what about something like this
`ggplot(df.df, aes(x=category, color=group)) +
stat_summary(aes(y = value),
fun.y = mean, na.rm = TRUE,
geom = "bar",
size = 3) +
stat_summary(aes(y = value),
fun.data = mean_se, na.rm = TRUE,
geom = "errorbar",
width = 0.2) `
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With