Search code examples
rggplot2dplyrfacet-wrap

Order facet_wrap plots by descending order


I am trying to plot with facet_wrap that by default is ordering the plots alphabetically. However, the desired result would be to order it by a numerically descending column.

Below is what I get:

library(tidyverse)

M <- data.frame(
    A = LETTERS[1:10],
    B = round(rnorm(10,200,50)), 
    C = letters[15:24]
  )

ggplot(M, aes(A, B)) + 
    geom_bar(stat = "identity") + 
    facet_wrap(~C)

Instead, I am looking to get the plots ordered by column B descending

arrange(M, desc(B)) %>%
    ggplot(aes(A, B)) + 
    geom_bar(stat = "identity") + 
    facet_wrap(~C)   ## need it ordered by B

I know one approach is to change the levels but I don´t know where in the sequence I can make it and how.


Solution

  • You can reorder the factor levels of C according to the values of B (in descending order) using forcats::fct_reorder or base reorder inside the facet_wrap:

    library(tidyverse)
    
    ## data
    M <- data.frame(
        A = LETTERS[1:10],
        B = round(rnorm(10,200,50)), 
        C = letters[15:24]
      )
    
    ## using fct_reorder
    ggplot(M, aes(x = A, y = B)) + 
        geom_bar(stat = "identity") + 
        facet_wrap(facets = ~fct_reorder(C, B, .desc = TRUE))
    
    ## using base reorder
    ggplot(M, aes(x = A, y = B)) + 
        geom_bar(stat = "identity") + 
        facet_wrap(facets = ~reorder(C, -B))   ## -B to get descending order