簡體   English   中英

按每個條形的唯一因素堆疊條形圖順序

[英]Stacked barplot order by unique factors per bar

我找到了諸如如何使用 ggplot2上的標識控制堆疊條形圖的排序這樣的帖子,其中當條形圖中具有相同因子時可以重新調整因子的順序,或者使用數字對堆疊條進行排序,但我想要創建一個堆疊條形圖,其中每個堆疊都有自己獨特的因素。

test <- data.frame(unique_factors = c("stack", "bars", "in", "this", "exact", "order"),
           length = c(1,5,3,2,6,1),
           groups = c("1", "1", "1", "2", "2", "2"))

ggplot(test, aes(x = groups, y = length)) +
  geom_bar(stat = "identity", aes(fill = unique_factors, levels=c("stack", "bars", "in", "this", "exact", "order")))

電流輸出

在此處輸入圖片說明

期望輸出

在此處輸入圖片說明

是否有可能達到這種效果 - 如果可以,如何實現? 非常感謝你的幫助!

您也可以使用forcats包:

fct_inorder將它們按照我們在 data.frame 中的順序放置,而fct_rev顛倒了順序:

library(forcats)
ggplot(test, aes(x = groups, y = length)) +
  geom_bar(stat = "identity",
           aes(fill = fct_rev(fct_inorder(unique_factors))))

在此處輸入圖片說明

我只需要重構 unique_factors!

test$unique_factors <- factor(test$unique_factors, levels = c("stack", "bars", "in", "this", "exact", "order"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM