Reputation: 85
I'm trying to create a barplot
with confidence interval error bars using ggplot
. Essentially, I have a variable, Q1
, with 7 answer options, and I want to plot the percent of respondents for each option, as a factor of two groups (One and Two) - the percent of subjects in each group that selected each of the 7 answer option.
I've tried adding y= count
, y=prop
or y=..prop..
to aes
in ggplot
, but it neither seem to work. Any suggestions are appreciated.
df5 <- filter(df, Q1!="-99",df$Group=="One"|df$Group=="Two")
ggplot(data = df5, aes(x = Q1)) +
stat_summary(fun.y = mean, geom = "bar") +
stat_summary(fun.data = mean_cl_boot, geom = "errorbar", fun.args = list(mult = 1)) +
geom_bar(aes(label= scales::percent(..prop..),
y= ..prop..,fill = df5$Group), position = "dodge")
Error: stat_summary requires the following missing aesthetics: y.
I'm essentially trying to get something that looks like this, with the error bars representing confidence intervals.
Upvotes: 1
Views: 4001
Reputation: 1254
Please note that there is a better way to write your first selection:
df5 <- df %>% filter(Q1!="-99", Group %in% c("One", "Two"))
I recommend you to compute the stats explicitly before making the graph. function DescTools::MultinomCI()
will do the job (cf documentation)
# Reproducible example: random
library(tidyverse)
n <- 1000
df5 <- tibble(
Q1 = sample(letters[1:7], n, replace=TRUE),
Group = sample(c("One","Two"), n, replace=TRUE)
)
library(DescTools)
df_stats <- df5 %>%
count(Group, Q1) %>%
group_by(Group) %>%
do({
df_grp <- .
df_grp %>%
select(Q1, n) %>%
bind_cols(as_tibble(MultinomCI(df_grp$n))) %>%
rename(prop = est)
})
If you want to use bar plots:
df_stats %>%
ggplot(aes(Q1, y=prop, ymin=lwr.ci, ymax=upr.ci, fill=Group)) +
geom_col(position="dodge") +
geom_errorbar(position="dodge") +
ylim(0, NA)
(Note that axes of barplots should always start from zero, hence the use of ylim
)
However, in order to underline between-group differences in the answers, a line plot will be much more readable:
df_stats %>%
ggplot(aes(Q1, y=prop, ymin=lwr.ci, ymax=upr.ci, color=Group, group=Group)) +
geom_line() +
geom_errorbar(position="dodge", width=.2) +
ylim(0, NA)
Upvotes: 1