r/Rlanguage • • Jun 26 '21

Plotting Proportions within Groups using ggplot2

/r/rstats/comments/o8iocq/plotting_proportions_within_groups_using_ggplot2/
3 Upvotes

1 comment sorted by

1

u/bluesphere Jun 27 '21

Try this:

library(tidyverse)

df <- mtcars |>
  group_by(am, gear) |>
  tally() |>
  mutate(
    prop = n / sum(n),
    am = as.factor(am),
    gear = as.factor(gear)
  )

plt <- ggplot(
  data = df, 
  aes(
    x = am,
    y = prop,
    fill = gear
  )
) +
  geom_bar(
    stat = "identity", 
    position = "dodge"
  )

plt

https://i.imgur.com/kQNJCW8.png

Created on 2021-06-27 by the reprex package (v2.0.0)