R: reorder factor levels for several individual plots

I am trying to create several separate graphs from the same data.frame with a different order of factor levels along the y axis for each graph. It is assumed that each graph should order the levels of factors by y in a decreasing manner.

I know that this can be done manually for each plot, but I am looking for a more efficient and elegant way, since I will have quite a few plots that I need to create. Should this not include using facet_wrap if there is another way, possibly with loops, etc.?

library(ggplot2)
library(dplyr)
data("diamonds")

Taking a dataset and aggregation at two levels of factors (clarity and section):

means <- diamonds %>%
group_by(clarity, cut) %>%
summarise(carat = mean(carat))

Here I change the order by one factor, but in the end I would like to reorder separately for each plot (by reducing the average clarity).

means$clarity <- reorder(means$clarity, means$carat, FUN = mean)

face_wrap. compare_flip .

ggplot(means, aes(x = clarity, y = carat)) +
  geom_col() +
  facet_wrap(~cut, ncol = 1) +
  coord_flip()

, , y . , ?

+6
1

, :

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), ...)
}

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()

+6

All Articles