2017-05-09 1 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") 

これはまだ動作しません。私は助けていただければ幸いです!各region内、我々ソートregionによってvalueを減少させることにより注文し、次いでvalueによって領域内に、次にレベルのソート順序と因子airportを変換する

答えて

2

は偉大な答えを持っていますが、私は多くの場合、自分がそれを行うために必要、プラスいくつかの他の変数に面取りを見つけるため、同様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

ここでWHE、私は秩序と面の両方を使用する必要があるかもしれない方法の例です私は自分の走行履歴を "FAC" という名前の別の列に+ facet_grid(~fac, scales = "free_x", space = "free_x")を追加RE:

enter image description here

4

。次に、ファセットを使用して各地域ごとに別々のパネルを取得します。 eipi10 @

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

うわー!お手伝いありがとう! (甘いフォーマットのボーナスポイント) –

関連する問題