簡體   English   中英

如何按 ggplot2/R 中填充類別之一的值對堆積條形圖 x 類別進行排序

[英]How to order stacked bar plot x categories by value of one of the fill categories in ggplot2/R

我試圖將我的數據繪制為具有 3 個級別(“catg”)的堆疊條形圖,但我希望 X 軸上的類別按“低”子類別的值按遞增順序出現,

這是生殖示例:

#creating df:
set.seed(33)
df<-data.frame(value=runif(12),
               catg=factor(rep(c("high","medium","low")),
                           levels = c("high","medium","low")),
               var_name=(c(rep("question1",3),rep("question2",3),rep("question3",3),rep("question4",3)))
#plotting
bar_dist<-ggplot(df,aes(x=var_name,
                              y=value, 
                              fill=catg, 
                             label=round(value,2)))

bar_dist+ geom_bar(stat = "identity",
                   position = "dodge", 
                   width = 0.7)+
  coord_flip() +
  xlab("questions")+
  ylab("y")+
  geom_text(size = 4,position=position_dodge(width = 0.7))

這是我目前的情節:

在此處輸入圖片說明

所以在這種情況下,我應該有問題 3,然后是 4、1,最后是 2。我們將不勝感激,

使用forcats庫中的fct_reorder2()不修改數據框的解決方案:

library(forcats)

bar_dist <- ggplot(df,
                   aes(
                     x = fct_reorder2(var_name, catg, value),
                     y = value, fill = catg, 
                     label = round(value, 2)))

bar_dist + geom_bar(stat = "identity",
                   position = "dodge", 
                   width = 0.7) +
  coord_flip() +
  xlab("questions") +
  ylab("y") +
  geom_text(size = 4, position = position_dodge(width = 0.7))

分組條形圖,列按跨組的一個變量的值排序

一種方法可能是:

df$var_name=factor(df$var_name,levels=rev(levels(reorder(df[df$catg=="low",]$var_name,df[df$catg=="low",]$value))))

它按照 Richard Telford 的建議使用reorder()在過濾df以僅保留"low"后根據df$value重新排序級別。
levels()用於從前一個函數中提取級別。
rev()用於反轉級別。
factor()將級別重新分配給df$var_name

或者 :

df$var_name=factor(df$var_name,levels = df[with(df,order(value,decreasing = T)) ,][df[with(df,order(value,decreasing = T)) ,]$catg=="low",]$var_name)

它排序dfdf$value (通過降低值),在過濾器df$catg"low" ,並檢索df$var_name其用作水平factor()

然后使用相同的繪圖函數:

在此處輸入圖片說明

暫無
暫無

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

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