R: reorder factor levels for several individual plots

前端 未结 1 1847
栀梦
栀梦 2021-02-09 12:21

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

1条回答
  •  无人及你
    2021-02-09 12:38

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

    0 讨论(0)
提交回复
热议问题