Reputation: 13
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()
Upvotes: 0
Views: 4303
Reputation: 46968
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)))
Upvotes: 1
Reputation: 2891
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")
Upvotes: 2