0

I have the following dataframe:

df <- tribble(
  ~age_group, ~count, ~outcome, ~g1, ~g2, ~g3,
  "first", 10, 110, 0.3, 0.6, 0.1,
  "second", 20, 70, 0.4, 0.3, 0.3,
  "third", 80, 35, 0.25, 0.5, 0.25
)

# # A tibble: 3 × 6
#   age_group count outcome    g1    g2    g3
#   <chr>     <dbl>   <dbl> <dbl> <dbl> <dbl>
# 1 first        10     110  0.3    0.6  0.1 
# 2 second       20      70  0.4    0.3  0.3 
# 3 third        80      35  0.25   0.5  0.25

ggplot(df, aes(x = age_group, y = outcome)) +
  geom_col()

I would like to have a bar plot with age_group on the x-axis, outcome on the y-axis. g1, g2, and g3 specify the fill proportions for the respective groups in each bar.

How can I specify these manual fill ratios?

Bonus if you can get the counts below the x-axis as so:

ggplot2: Adding sample size information to x-axis tick labels

dcsuka
  • 2,922
  • 3
  • 6
  • 27

1 Answers1

1

I manage to do what you need with a bit of data manipulation before plotting

df2 <- df %>%
        pivot_longer(cols = c(-age_group,-outcome, -count),
                        names_to = "group") %>%
        mutate(outcome2 = outcome * value,
               age_group2 = paste(age_group, paste("N = ",count), sep="\n"))


ggplot(df2, aes(x = age_group2,
                y = outcome2, 
                fill = group)) +
        geom_col(show.legend = F)+
        geom_text(aes(label = group),
                  position = position_stack(0.5), 
                  color = 'white')

enter image description here

Lucca Nielsen
  • 1,497
  • 3
  • 16