Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 642
Jonathan Livingston Seagull Avatar asked Dec 22 '25 04:12

Jonathan Livingston Seagull


1 Answers

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

like image 64
Joris C. Avatar answered Dec 24 '25 11:12

Joris C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!