0

Is there a way to order the bars in geom_bar() when y is just the count of x?

Example:

ggplot(dat) +
  geom_bar(aes(x = feature_1)) 

I tried using reorder() but it requires a defined y variable within aes().

Phil
  • 7,287
  • 3
  • 36
  • 66
Saffra
  • 15
  • 4
  • Not 100% sure whether there is a way to achieve this with geom_bar ... instead I would go for the easy solution and pre-compute the counts. – stefan Aug 24 '20 at 19:38
  • Kind of similar to this: https://stackoverflow.com/questions/25664007/reorder-bars-in-geom-bar-ggplot2 My answer below based on this link – greg dubrow Aug 25 '20 at 00:02

1 Answers1

0

Made up data:

dfexmpl <- data.frame(stringsAsFactors = FALSE,
         group = c("a","a","a","a","a","a",
                   "a","a","a","b","b","b","b","b","b","b","b","b",
                   "b","b","b","b","b","b"))

plot code - reorder is doing the work of arranging by count:

dfexmpl %>%
group_by(group) %>%
mutate(count = n()) %>%
ggplot(aes(x = reorder(group, -count), y = count)) +
geom_bar(stat = "identity")

results in: enter image description here

greg dubrow
  • 623
  • 6
  • 9