I am trying to create several individual plots from the same data.frame with a different order of the factor levels on the y axis for each plot. Each plot is supposed to order t
This can be done in one plot by utilizing two functions:
reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) {
new_x <- paste(x, within, sep = sep)
stats::reorder(new_x, by, FUN = fun)
}
scale_x_reordered <- function(..., sep = "___") {
reg <- paste0(sep, ".+$")
ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...)
}
available on github dgrtwo/drlib
ggplot(means, aes(x = reorder_within(clarity, carat, cut, mean), y = carat)) +
geom_col() +
scale_x_reordered() +
facet_wrap(~cut, scales = "free_y", ncol = 1) +
coord_flip()