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

Eri*_*ric 2 r ggplot2

我正在尝试使用 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
Run Code Online (Sandbox Code Playgroud)

我想在 x 轴上绘制每个组,并由每个成功级别的观察比例填充。

ggplot(my_data, aes(x = group, fill = success)) +
  geom_bar(position = 'fill')
Run Code Online (Sandbox Code Playgroud)

有什么方法可以对我的组进行重新排序,以便它们按成功比例的升序(或降序)顺序显示?

Wal*_*ldi 5

fct_reorder从包中使用forcats

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

它所做的就是group根据成功率mean进行重新排序。success=='yes'

您可以使用 .desc 参数反转顺序。