小编Eri*_*ric的帖子

fct_reorder() 仅适用于一个方面

我正在尝试创建一个多面条形图,其中条形根据频率排序(使用 fct_reorder)。这是我的代码:

\n\n
word_count_label <- twitter_sm %>%\n  group_by(complaint) %>%\n  summarize_if(is.numeric, sum) %>%\n  ungroup() %>%\n  gather(word, n, -complaint) %>%\n  mutate(word = as.factor(word)) %>%\n  filter(n > 0) %>%\n  group_by(complaint) %>%\n  mutate(word = fct_reorder(word, n)) %>%\n  top_n(20, n) %>%\n  arrange(complaint, desc(n)) %>%\n  ungroup()\n
Run Code Online (Sandbox Code Playgroud)\n\n

生成的数据框如下所示:

\n\n
   complaint     word              n\n   <fct>         <fct>         <dbl>\n 1 non_complaint klm             820\n 2 non_complaint flight          653\n 3 non_complaint unit            537\n 4 non_complaint americanair     532\n 5 non_complaint delta           441\n 6 non_complaint thank           420\n 7 non_complaint southwestair    363\n 8 non_complaint britishairway …
Run Code Online (Sandbox Code Playgroud)

r ggplot2 forcats

3
推荐指数
1
解决办法
489
查看次数

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

我正在尝试使用 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)

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

r ggplot2

2
推荐指数
1
解决办法
604
查看次数

标签 统计

ggplot2 ×2

r ×2

forcats ×1