library(tidyr)
library(ggplot2)
iris_gathered <- gather(iris, metric, value, -Species)
# reordering doesn't work within each facet (see Sepal.Width):
ggplot(iris_gathered, aes(reorder(Species, value), value)) +
geom_boxplot() +
facet_wrap(~ metric)
# reorder_within and scale_x_reordered work.
# (Note that you need to set scales = "free_x" in the facet)
ggplot(iris_gathered, aes(reorder_within(Species, value, metric), value)) +
geom_boxplot() +
scale_x_reordered() +
facet_wrap(~ metric, scales = "free_x")
# to reorder within multiple variables, set within to the list of
# facet variables.
ggplot(mtcars, aes(reorder_within(carb, mpg, list(vs, am)), mpg)) +
geom_boxplot() +
scale_x_reordered() +
facet_wrap(vs ~ am, scales = "free_x")
Run the code above in your browser using DataLab