首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fct_reorder()只对一个方面正常工作

fct_reorder()只对一个方面正常工作
EN

Stack Overflow用户
提问于 2020-05-23 02:13:26
回答 1查看 85关注 0票数 1

我正在尝试创建一个分面条形图,条形图根据它们的频率排序(使用fct_reorder)。下面是我的代码:

代码语言:javascript
复制
word_count_label <- twitter_sm %>%
  group_by(complaint) %>%
  summarize_if(is.numeric, sum) %>%
  ungroup() %>%
  gather(word, n, -complaint) %>%
  mutate(word = as.factor(word)) %>%
  filter(n > 0) %>%
  group_by(complaint) %>%
  mutate(word = fct_reorder(word, n)) %>%
  top_n(20, n) %>%
  arrange(complaint, desc(n)) %>%
  ungroup()

生成的数据框如下所示:

代码语言:javascript
复制
   complaint     word              n
   <fct>         <fct>         <dbl>
 1 non_complaint klm             820
 2 non_complaint flight          653
 3 non_complaint unit            537
 4 non_complaint americanair     532
 5 non_complaint delta           441
 6 non_complaint thank           420
 7 non_complaint southwestair    363
 8 non_complaint britishairway   326
 9 non_complaint just            294
10 non_complaint usairway        261
# … with 30 more rows

然而,当我创建了一个刻面条形图来绘制每个刻面的字数时(代码如下所示),

代码语言:javascript
复制
  ggplot(word_count_label, aes(x = word, y = n, fill = complaint)) +
  geom_col() + coord_flip() + 
  facet_wrap(~complaint, scales = 'free_y')

绘图仅对一个面的条形图进行排序:

有没有人知道为什么会发生这种情况?谢谢!

EN

回答 1

Stack Overflow用户

发布于 2020-05-23 02:21:27

您可以使用tidytext包中的reorder_within()而不是fct_reorder()。Julia Silge有一个很好的here例子。

代码语言:javascript
复制
word_count_label <- twitter_sm %>%
  group_by(complaint) %>%
  summarize_if(is.numeric, sum) %>%
  ungroup() %>%
  gather(word, n, -complaint) %>%
  mutate(word = as.factor(word)) %>%
  filter(n > 0) %>%
  mutate(word = reorder_within(word, n, complaint)) %>%
  group_by(complaint) %>%
  top_n(20, n) %>%
  arrange(complaint, desc(n)) %>%
  ungroup()

此外,Julia使用scale_x_reordered()作为ggplot中的层。下面是一个示例:

代码语言:javascript
复制
ggplot(word_count_label, aes(x = word, y = n, fill = complaint)) +
  geom_col() + 
  coord_flip() + 
  scale_x_reordered() + 
  facet_wrap(~complaint, scales = 'free_y')
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61961370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档