r - 使用 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()
排序现在丢失了,十个单词以(对我来说)随机顺序出现。为什么排序会丢失?我是否错误地使用了命令?
解决方案
首先,您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()
推荐阅读
- angular - 如何从 Azure Blob Storage (V2) 获取数据到 Angular 7?
- json - 可编码的 HAL JSON 类型
- api - 如何使用在邮递员中运行按钮编辑/更新环境变量?
- r - R中列上的变异函数循环
- python - 在window10上使用conda安装yolov3时出现错误解决环境:失败
- excel - 禁用 DDE 警告
- java - aws ecs 使用容器覆盖运行 ecs 任务
- python - Python(Jupyter Notebook):显示条形图,列作为图例,索引作为 x-ticks
- machine-learning - keras ANN 中的输入和输出形状
- javascript - 如何将 React Hook useState 与自定义实体对象一起使用?