首页 > 解决方案 > 使用 top_n 后,R 在管道期间丢失排序

问题描述

我有一个带有列的数据框,word我想在带有 ggplot 的条形图中显示文本中的前 10 个单词。

这是代码:

text_df %>% count(word, sort = TRUE) %>% top_n(10)

结果符合预期。现在我想在图中显示:

text_df %>% count(word, sort = TRUE) %>% top_n(10) >%>
ggplot(aes(word, n)) + geom_col()

排序现在丢失了,十个单词以(对我来说)随机顺序出现。为什么排序会丢失?我是否错误地使用了命令?

标签: r

解决方案


首先,您ggplot失去排序的原因是因为ggplot期望输入是具有水平的因素。

fct_reorder在绘图和发送到 ggplot 之前从库中使用forcats,将对您面临的问题进行排序

library(forcats)
library(ggplot2)
temp %>% count(word, sort = TRUE) %>% top_n(10) %>% 
mutate(word=fct_reorder(word,-n)) %>%   
ggplot(aes(word, n)) + geom_col()

推荐阅读