2017-05-09 102 views
2

我試圖在變量中對變量進行分組並按降序排序。在ggplot2中訂購多個變量

是myDF

region airport value 
MIA   FLL 0.244587909 
MIA   PBI 0.824144687 
MIA   MIA 0.484907626 
NYC   EWR 0.731075565 
NYC   LGA 0.708648915 
NYC   HPN 0.523991258 
LAX   LGB 0.651847818 
LAX   LAX 0.423607479 
LAX   SNA 0.433837044 
LAX   ONT 0.723144957 
Other MCO 0.657586674 
Other SJC 0.084138321 
Other OAK 0.698794154 
Other BOS 0.85765002 
Other BNA 0.018953126 
Other WAS 0.234897245 

https://i.stack.imgur.com/G1E2k.jpg

enter image description here

我想重現上圖。

這是第一個嘗試:

ggplot(mydf, aes(x=airport,y=value, fill = region)) + 
    geom_bar(stat = "identity") 

這裏是第2次嘗試:

ggplot(mydf, aes(x=reorder(airport,-value,sum),y=value, fill = region)) + 
    geom_bar(stat = "identity") 

我卡在這裏。我可以嵌套重新訂購嗎? reorder(reorder(x, y), y)我不想讓這是一個手動過程來調出每個分組。

This is as far as I can get

mydf$order <- c('ONT','LGB','SNA','LAX','PBI','MIA','FLL','EWR','LGA','HPN','BOS','OAK','MCO','WAS','SJC','BNA') 

ggplot(mydf, aes(x=airport,y=value, fill = region, order = order)) + 
    geom_bar(stat = "identity") 

這仍然無法正常工作。我會很感激任何幫助!

回答

2

@ eipi10有一個偉大的答案,但我經常發現自己需要做的是,加磨製一些其他的變量,所以有其他的選擇,以及用forcats包:

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

enter image description here

這裏是我可能需要同時使用排序和麪,磨片的例子再我添加+ facet_grid(~fac, scales = "free_x", space = "free_x")與名爲「FAC」我的旅行史的另一列:

enter image description here

4

由各region內減少value區域內訂購,我們排序region然後value,然後轉換airport的因素與水平的排序順序。然後,我們使用刻面爲每個區域獲得單獨的面板。

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

enter image description here

+0

哇!感謝您的幫助! (甜蜜格式的獎勵積分) –