2017-10-11 198 views
0

我想創建一個簡單的水平barplot閃動酒吧,但我很(水平)酒吧的排序struggeling。當我做一個正常的barplot(堆疊或閃避)時,我可以通過設置有用的因子級別並根據相應的變量對數據幀進行排序,從而輕鬆控制條形圖的順序。但是,排序數據框似乎對水平圖中條的順序沒有任何影響。 我發現了一些類似的問題,但我不確定它們是否對應我的問題(情節看起來有點不同)。R ggplot水平閃避barplot訂單

df1 <- data.frame (year = as.factor(c(rep(2015,3),rep(2016,3),rep(2017,3))), 
value = c(50,30,20,60,70,40,20,50,80), 
set = rep(c("A","B","C"),3)) 

ggplot() + geom_bar(data= df1, aes(y=value, x=set, fill=year), 
stat="identity", position="dodge") + 
coord_flip() 

我想要的是一個水平圖,顯示2015年酒吧在上面和2017年酒吧在底部。有趣的是,當我離開coord_flip()時,酒吧是以這種方式排列的,但我需要情節是水平的。 訂貨數據這種方式不會改變劇情:

df1 <- df1[rev(order(df1$year)),] 

我任何提示:)

回答

2

你打GGPLOT2的特質之一感激 - 酒吧coord_flip後的排序得到了有點不直觀。要改變它,你必須在df1$year中顛倒你的因子水平的順序,而不僅僅是這些值本身。請看下圖:

library(ggplot2) 

df1 <- data.frame (year = as.factor(c(rep(2015,3),rep(2016,3),rep(2017,3))), 
        value = c(50,30,20,60,70,40,20,50,80), 
        set = rep(c("A","B","C"),3)) 

levels(df1$year) 
#> [1] "2015" "2016" "2017" 

df1$year <- factor(df1$year, levels = rev(levels(df1$year))) 

ggplot(df1) + 
    geom_bar(aes(y=value, x=set, fill=year), 
      stat="identity", position="dodge") + 
    coord_flip() 

如果你想保持你的傳奇在原來的順序,你可以用guide_legend訪問此。

ggplot(df1) + 
    geom_bar(aes(y=value, x=set, fill=year), 
      stat="identity", position="dodge") + 
    guides(fill = guide_legend(reverse = TRUE)) + 
    coord_flip() 

+0

完美,太感謝你了!我試着改變因子水平,但是指南(fill = guide_legend(reverse = TRUE))確實有效。前段時間我有類似的問題,但完全忘記了這個改變傳說順序的漂亮線條:) – Aki