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

プロットは、1 つのファセットのバーのみを並べ替えます。

ここに画像の説明を入力

なぜこれが起こっているのかについての洞察を持っている人はいますか? ありがとう!

4

1 に答える 1