簡體   English   中英

按另一個因素重新排序因素水平

[英]Reorder Factor Levels By Another Factor

我正在嘗試使用 ggplot2 創建條形圖,其中條形按填充因子的某個水平的觀察比例排序。 例如,假設我有如下數據:

my_data <- data.frame(group = as.factor(rep(1:3, each = 5)), success = as.factor(c('yes','yes','yes','yes','no','yes','yes','no','no','no','yes','no','no','no','no')))

   group success
1      1     yes
2      1     yes
3      1     yes
4      1     yes
5      1      no
6      2     yes
7      2     yes
8      2      no
9      2      no
10     2      no
11     3     yes
12     3      no
13     3      no
14     3      no
15     3      no

我想在 x 軸上的每組 plot 填充每個成功級別的觀察比例。

ggplot(my_data, aes(x = group, fill = success)) +
  geom_bar(position = 'fill')

有什么方法可以重新排序我的組,以便它們以成功比例的升序(或降序)順序顯示?

使用來自fct_reorder forcats的 fct_reorder:

ggplot(my_data, aes(x = forcats::fct_reorder(group,success == 'yes',mean,.desc = T), fill = success)) +
  geom_bar(position = 'fill')+
  xlab("group")

它的作用是根據success=='yes' meangroup進行重新排序,這給出了成功率。

您可以使用 .desc 參數反轉順序。

我們可以得到按'group'分組后的比例

library(dplyr)
library(ggplot2)
my_data %>% 
  group_by(group) %>% 
  mutate(prop = mean(success == 'yes')) %>%
  ungroup %>%
  ggplot(aes(x = reorder(group, prop), fill = success)) + 
       geom_bar(position = 'fill') +
       xlab('group')

暫無
暫無

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

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