Percent bar chart

This feels like a basic question, but I'm struggling to find a recent answer online. I'd like to create a bar chart where the label on the y axis is the percent of the total for that group. With geom_bar() there's no obvious way to change the labels, and for geom_col() I have to pre-aggregate my data. Is there a way to make a simple geom_bar() but have the labels on the y axis be percents?

library(tidyverse)
data("diamonds")

# bar chart with totals on y
ggplot(diamonds) +
  geom_bar(aes(x = color))


# bar chart with percents on y
diamonds |>
  count(color) |>
  mutate(percent = n / sum(n)) |>
  ggplot() +
  geom_col(aes(x = color, y = percent)) +
  scale_y_continuous(labels = scales::label_percent())

Created on 2024-03-14 with reprex v2.1.0

This works, but it might not do what you want if the data has NA values.

ggplot(diamonds) +
  geom_bar(aes(x = color, y = after_stat(count)/nrow(diamonds))) + 
  scale_y_continuous(labels = scales::label_percent())

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.