【问题标题】:R loses sorting during pipe after using top_n [duplicate]R在使用top_n后在管道期间丢失排序[重复]
【发布时间】:2020-01-16 02:41:41
【问题描述】:

我有一个带有 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()

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

【问题讨论】:

  • 试试text_df %>% count(word, sort = TRUE) %>% top_n(10) %>% mutate(word = forcats::fct_inorder(word))。这将通过使word 和有序因子“锁定”排序,按照它出现在排序输出中的顺序。

标签: r


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2011-10-03
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2014-04-05
    • 2023-02-02
    • 2023-03-03
    相关资源
    最近更新 更多