2

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!

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.