library(tidyverse)
# Create a dataset that is similar to yours.
df1 <-
tibble(
y = 1:10,
women_v1 = abs(rnorm(10)),
women_v2 = abs(rnorm(10)),
men_v1 = abs(rnorm(10)),
men_v2 = abs(rnorm(10))
)
# Pivot the dataset longer and derive `sum` and `sd` for the plot.
df2 <-
df1 |>
pivot_longer(-y, names_to = c("sex", "var"), names_sep = "_") |>
summarise(
sd = sd(value, na.rm = TRUE),
value = sum(value),
.by = c(sex, var)
)
# Create a barplot with errorbars.
ggplot(df2, aes(x = var, y = value, fill = sex)) +
geom_bar(stat = "identity",
color = "black",
position = position_dodge()) +
geom_errorbar(aes(ymin = value, ymax = value + sd),
width = .2,
position = position_dodge(.9))