Order multiple variables in ggplot2

前端 未结 3 1070
轮回少年
轮回少年 2021-02-15 23:59

I\'m attempting to group variables within variables and sort in descending order.

mydf

region  airport value
MIA         FLL 0.244587909
MIA         PBI         


        
3条回答
  •  耶瑟儿~
    2021-02-16 00:14

    @eipi10 has a great answer, but I often find myself needing to do that, plus facetting on some other variable, so there are other options as well using the forcats package:

    require(dplyr)
    require(forcats)
    
    mydf %>% 
      mutate(ordering = -as.numeric(region) + value,
             airport = fct_reorder(airport, ordering, .desc = T)) %>% 
      ggplot(aes(airport, value, fill = region)) + geom_col()
    

    Here's an example of how I might need to use both the ordering and the facets, where I add + facet_grid(~fac, scales = "free_x", space = "free_x") with another column named "fac" with my travel history:

提交回复
热议问题