Bar chart with values

Hi all,

I'm trying to create a bar chart of proportions with value labels for each bar and different bar colors. Right now here's what I have

library(tidyverse)
ggplot(data = mpg, mapping = aes(x = factor(cyl), fill = factor(cyl))) + 
  geom_bar() +
  geom_text(mapping = aes(label = ..prop.., group=1), stat = "count", vjust=-.5) 

When I run this code it sort of gives me almost everything I want, except that I can't, however, seem to figure out how to change the y-axis to show proportion instead of count. I appreciate any suggestion. Thanks!

to get the proportions you want stat_count() requires to have just one group so you cant apply fill = cyl, if you want more flexibility, calculate the proportions yourself and use geom_col()

library(tidyverse)

ggplot(data = mpg) +
    geom_bar(mapping = aes(x = factor(cyl), y = stat(prop), group = 1), stat = "count") +
    geom_text(mapping = aes(label = stat(scales::percent(prop)), x = factor(cyl), y = stat(prop), group=1), stat = "count", vjust=-.5)

mpg %>% 
    group_by(cyl) %>% 
    summarise(n = n(), .groups = "drop") %>%
    mutate(cyl = factor(cyl), prop = n/sum(n)) %>% 
    ggplot(aes(x = cyl, y = prop, fill = cyl)) +
    geom_col() + 
    geom_text(aes(label = scales::percent(prop)))

Created on 2021-09-10 by the reprex package (v2.0.1)

1 Like

Calculating the proportions separately works. I was just wondering if there is a way to plot using the original data set without having to go through that intermediate step. If there's not, that's not a big deal. Thanks!

I just remembered the recently added stage() function

library(tidyverse)

ggplot(data = mpg) +
    geom_bar(mapping = aes(x = factor(cyl), y = stat(prop), group = stage(1, after_stat = factor(x)), fill = stage("x", after_stat = factor(x)))) +
    geom_text(mapping = aes(label = stat(scales::percent(prop)), x = factor(cyl), y = stat(prop), group=1),
              stat = "count",
              vjust=-.5)

Created on 2021-09-12 by the reprex package (v2.0.1)

1 Like

This is awesome. Could you please point me to some resources where I can learn some more about the stage() function and also the stat argument? I feel like I'm not having a good grasp of either. Thanks so much!

This topic was automatically closed 7 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.