0

我正在浏览网站https://www.tidytextmining.com并尝试使用奥斯汀图书数据集。我正在尝试绘制六本书中最常见的单词,并让每个情节的各个条按降序排列。我已经修改了代码以绘制第 3.3 节中显示的 tf-idf,但我无法让这些图看起来相同(让单词频率的条形按降序排列)。可重现的代码和输出如下所示。

needed <- c("plyr", "dplyr", "tidytext", "ggplot2", "janeaustenr")
install.packages(needed, dependencies=TRUE)
list = lapply(needed, require, character.only = TRUE)

data(stop_words)

book_words = austen_books() %>%
    unnest_tokens(word, text) %>%
    anti_join(stop_words) %>%
    count(book, word, sort = TRUE) %>%
    ungroup()

total_words = book_words %>% 
    group_by(book) %>% 
    summarize(total = sum(n))

book_words = left_join(book_words, total_words)

book_words <- book_words %>%
    bind_tf_idf(word, book, n)

book_words %>%
    arrange(desc(n)) %>%
    mutate(word = factor(word, levels = rev(unique(word)))) %>% 
    group_by(book) %>% 
    top_n(15, wt = n) %>% 
    ungroup %>%
    ggplot(aes(word, n, fill = book)) +
    geom_col(show.legend = FALSE) +
    labs(x = NULL, y = "n") +
    facet_wrap(~book, ncol = 2, scales = "free") +
    coord_flip()

生成的 Rplot

4

0 回答 0