我正在尝试创建一个分面条形图,条形图根据它们的频率排序(使用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')绘图仅对一个面的条形图进行排序:

有没有人知道为什么会发生这种情况?谢谢!
发布于 2020-05-23 02:21:27
您可以使用tidytext包中的reorder_within()而不是fct_reorder()。Julia Silge有一个很好的here例子。
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中的层。下面是一个示例:
ggplot(word_count_label, aes(x = word, y = n, fill = complaint)) +
geom_col() +
coord_flip() +
scale_x_reordered() +
facet_wrap(~complaint, scales = 'free_y')https://stackoverflow.com/questions/61961370
复制相似问题