我正在浏览网站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()