There's a lot of examples around of how to alter the sort order of groups in ggplot
. They generally look like this:
Default Sorting:
library(tidyverse)
mt <- mtcars
mt$carb2 <-
factor(mtcars$carb, levels = rev(levels(factor(mtcars$carb))))
p <- ggplot(data = mt, aes(y = carb2, x = mpg, colour = hp)) +
geom_point()
p
Reverse sorting
p + scale_y_discrete(limits = rev(sort(unique(mt$carb2))))
Which works great, assuming you're doing a script and can know ahead of time the values going into the y
axis. I'm working on a function and the y
is built with a bunch of branching logic depending on the inputs. So is there a way to "reach inside" the p
object above and extract out the y
so I can resort it and feed it back into scale_y_discrete
?
It seems like I could traverse the p
object in some way and then evaluate the internal quosures. But I have to admit, I have never done anything like that and sort of don't know where to start.