2

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

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()

生成的数据框如下所示:

   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

但是,当我创建一个分面条形图绘制每个方面的字数时(代码如下所示),

  ggplot(word_count_label, aes(x = word, y = n, fill = complaint)) +
  geom_col() + coord_flip() + 
  facet_wrap(~complaint, scales = 'free_y')

该图只为一个方面订购条形图:

在此处输入图像描述

有没有人对为什么会发生这种情况有任何见解?谢谢!

4

1 回答 1

4

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

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()

此外,Juliascale_x_reordered()在 ggplot 中用作图层。这是一个示例:

ggplot(word_count_label, aes(x = word, y = n, fill = complaint)) +
  geom_col() + 
  coord_flip() + 
  scale_x_reordered() + 
  facet_wrap(~complaint, scales = 'free_y')
于 2020-05-22T18:21:27.490 回答