0

Say I use the following to produce the bar graph below. How would I only visualize bars where the count is above, say, 20? I'm able to do this kind of filtering with the which function on variables I create or that exist in my data, but I'm not sure how to access/filter the auto-counts generated by ggplot. Thanks.

g <- ggplot(mpg, aes(class))
g + geom_bar()

Simple bar graph

litcomp
  • 13
  • 1
  • 4
  • 1
    Not sure how to do this, I agree with MSR below that the easy solution is just to aggregate the data beforehand. However, as we can see with geom_text, it should be possible to access the count to throw it on a filter `ggplot(mpg, aes(class)) + geom_bar() + geom_text(stat = 'count', aes(label=..count..))` – Lief Esbenshade Nov 13 '19 at 19:04

2 Answers2

2

Aggregating and filtering your data before plotting and using stat = "identity" is probably the easiest solution, e.g.:

library(tidyverse)

mpg %>% 
  group_by(class) %>%
  count %>%
  filter(n > 20) %>%
  ggplot(aes(x = class, y = n)) + 
  geom_bar(stat = "identity")
MSR
  • 2,731
  • 1
  • 14
  • 24
1

You can try this, so the auto-counts are ..count.. in aes (yes I know it's weird, you can see Special variables in ggplot (..count.., ..density.., etc.)). And if you apply an ifelse, that makes it NA if < 20, then you have your plot.. (not very nice code..)

g <- ggplot(mpg, aes(class))
g + geom_bar(aes(y = ifelse(..count.. > 20, ..count.., NA)))
StupidWolf
  • 45,075
  • 17
  • 40
  • 72