0

I am trying to create a grouped bar chart with 4 bars in total (wish of men with no support, wish of women with no support, wish of men who received support, wish of women who received support), plus error bars. The variable "wish" is measured on a scale from 1-5 so I am trying to set the limits accordingly, but this leads to only the error bars but not "main" bars being displayed in the graph, and following error message occurs:

Warning message: Removed 4 rows containing missing values (geom_bar()).

ggplot(wish_c, aes(x=factor(esnonrom_t,
                            levels = c("0", "1"),
                            labels = c("Received no support (n = 89)", "Received support (n=795)")), 
                   y=wish_for_partner_t1, 
                   fill=factor(sex_gen, 
                               levels = c("0", "1"), 
                               labels=c("Men (n=427)", "Women(n=457)")))) +
  geom_bar(position=position_dodge(), stat="identity")  +
  geom_errorbar(aes(ymin=wish_t1-se, ymax=wish_t1+se),
                width=.2,                    # Width of the error bars
                position=position_dodge(.9)) +
  scale_y_continuous("Wish (1-5)", limits=c(1,5), breaks=seq(1,5, by =1)) +
  theme_classic() +
  scale_fill_brewer(palette = "Greys") +
  labs(x = "Emotional support received 
       beyond the romantic relationship",
       fill = "Gender",
       title = "Wish by gender and emotional support") 

stefan
  • 90,330
  • 6
  • 25
  • 51
Iris W
  • 1
  • 1
  • 1
    Welcome to SO! A `geom_bar` starts a 0. Hence, when setting the limits to start at 1 the bars get dropped as they do not fit inside the limits. You could try with setting the limits via `coord_cartesian` instead. For more help please provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan May 18 '23 at 13:23

1 Answers1

0

One way to get this is to use stat_summary().

I have created a sample data set:

library(dplyr)
library(ggplot2)
library(tidyr)

set.seed(123)  

# example dataset
df <- data.frame(
  group = rep(c("Men - No Support", "Women - No Support", "Men - Support", "Women - Support"), each = 25),
  wish = round(runif(100, min = 1, max = 5), 1), 
  group2 = 
)

df %>% 
  separate(group, into = c("sex", "Support"), sep = " - ") %>% 
  ggplot(., aes(x = sex, wish, fill = Support))+
  stat_summary(fun= "mean", geom="col", position = "dodge")+
  stat_summary(fun.data = "mean_se", geom = "errorbar", width = 0.2, 
               position = position_dodge(width = 0.9))+
  theme_classic()

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66