Order multiple variables in ggplot2

前端 未结 3 991
轮回少年
轮回少年 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:32

    To order by decreasing value within each region, we sort by region and then by value within region and then convert airport to a factor with the sorted ordering of the levels. Then, we use faceting to get separate panels for each region.

    library(tidyverse)
    
    ggplot(mydf %>% arrange(region, desc(value)) %>%
             mutate(airport=factor(airport, levels=airport)), 
           aes(x=airport,y=value, fill = region)) +
      geom_bar(stat="identity", show.legend=FALSE) +
      geom_text(aes(label=round(value,2), y=0.5*value), colour="white", size=3) +
      facet_grid(. ~ region, scales="free_x", space="free_x") +
      scale_y_continuous(limits=c(-0.005, 1.05*max(mydf$value)), expand=c(0,0)) +
      theme_classic() +
      theme(panel.spacing=unit(0,"pt"), 
            panel.border=element_rect(colour="grey50", fill=NA))
    

提交回复
热议问题