2017-03-10 29 views
5

我使用ggplot這樣創建堆積條形圖:反向疊置條爲了

plot_df <- df[!is.na(df$levels), ] 
ggplot(plot_df, aes(group)) + geom_bar(aes(fill = levels), position = "fill") 

,給了我這樣的事情:

enter image description here

如何顛倒順序堆疊的酒吧本身,所以1級在底部,5級在每個酒吧的頂部?

我已經看到了一些關於這個問題(比如How to control ordering of stacked bar chart using identity on ggplot2)和常見的解決方案似乎是重新排序由該級別的數據幀作爲什麼ggplot使用確定的順序

所以我使用dplyr嘗試重新排序:

plot_df <- df[!is.na(df$levels), ] %>% arrange(desc(levels))

然而,劇情出來的一樣。它也似乎不有所作爲我無論是升序或降序

這裏安排是重複的例子:

group <- c(1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4) 
levels <- c("1","1","1","1","2","2","2","2","3","3","3","3","4","4","4","4","5","5","5","5","1","1","1","1") 
plot_df <- data.frame(group, levels) 

ggplot(plot_df, aes(group)) + geom_bar(aes(fill = levels), position = "fill") 
+0

觀察順序沒有意義,但因子水平的順序確實如此。另外,代表。 – alistaire

+0

是的,我也嘗試用'levels(plot_df $ levels)< - c(「1」,「2」,「3」,「4」,「5」)(和倒序)但它不會改變圖表順序 – Simon

+0

還添加了一個數據示例 – Simon

回答

16

The release notes of ggplot2 version 2.2.0 on Stacking bars suggest

如果你想在堆棧相反的順序,儘量forcats::fct_rev()

library(ggplot2) # version 2.2.1 used  
plot_df <- data.frame(group = rep(1:4, 6), 
         levels = factor(c(rep(1:5, each = 4), rep(1, 4)))) 
ggplot(plot_df, aes(group, fill = forcats::fct_rev(levels))) + 
    geom_bar(position = "fill") 

Reverse levels

這是原作情節

ggplot(plot_df, aes(group, fill = levels)) + 
    geom_bar(position = "fill") 

Original plot

或者,使用position_fill(reverse = TRUE)的建議通過alistaire in his comment

ggplot(plot_df, aes(group, fill = levels)) + 
    geom_bar(position = position_fill(reverse = TRUE)) 

enter image description here

請注意,圖例中的級別(顏色)與堆疊酒吧中的級別不同。