Shujun Ou
Shujun Ou

Reputation: 31

R ggplot geom_bar count number of values by groups

I tried this code without faceting, it works.

I want to add counts on each bar and use facets in my plot, it brokes. I managed to make it close to what I want, like this:

mtcars %>% group_by(gear, am, vs) %>% summarize(hp_sum = sum(hp), hp = hp) %>%
ggplot(aes(gear, hp_sum, fill = factor(am))) + facet_grid(.~vs) + 
  geom_bar(stat = 'identity', position = 'dodge', alpha = 0.5, size = 0.25) +
  geom_text(aes(label=..count.., y = ..count..), stat='count', position = position_dodge(width = 0.95), size=4)

enter image description here

But I want the number on top of each bar. If I use y = hp_sum, I got error:

Error: stat_count() can only have an x or y aesthetic.
Run `rlang::last_error()` to see where the error occurred.

I might have format the dataset in the wrong way. Any ideas? Thanks!

Upvotes: 2

Views: 4245

Answers (1)

Shujun Ou
Shujun Ou

Reputation: 31

I learned from this post that geom_text does not do counts by groups.

A solution is to do the summary beforehand:

mtcars %>% group_by(gear, am, vs) %>% 
  summarize(hp_sum = sum(hp), count = length(hp)) %>% 
  ggplot(aes(gear, hp_sum, fill = factor(am))) + facet_grid(.~vs) +
  geom_bar(stat = 'identity', position = 'dodge', alpha = 0.5, size = 0.25) +
  geom_text(aes(gear, hp_sum, label = count), 
            position = position_dodge(width = 0.95), size=4)

Be sure to group data the same way in the plot. Here x=gear, facet_grid(.~vs), fill = factor(am) are three factors putting y=hp into groups. So you should group this way: group_by(gear, am, vs). Hope this helps anyone who is struggling with this issue.

plot example

Upvotes: 1

Related Questions