我正试图以某种方式制作几个wordcloud的子图/方面 赏心悦目。
问题:
wordcloud
- 正确输出ggplot2
制作wordclouds允许进行分面处理,但会产生令人不满意的结果
(丑陋的定位)我尝试过两种方法来创建这些wordcloud-subplots。
library(dplyr)
library(janeaustenr)
library(tidytext)
df <- austen_books() %>%
unnest_tokens(word, text) %>%
anti_join(stop_words, by = "word") %>%
group_by(book) %>%
count(word) %>%
top_n(100, n)
wordcloud
包和基础R:library(wordcloud)
par(mfrow = c(2,2))
png("jane_austen_wordclouds.png")
df %>%
filter(book == "Sense & Sensibility") %>%
with(wordcloud(word, n))
df %>%
filter(book == "Pride & Prejudice") %>%
with(wordcloud(word, n))
df %>%
filter(book == "Mansfield Park") %>%
with(wordcloud(word, n))
df %>%
filter(book == "Emma") %>%
with(wordcloud(word, n))
title( "Jane Austen Word Clouds", outer = TRUE)
dev.off()
创建:
所以它不知何故只保存了最后一个子图。如果我不使用png("jane_austen_wordclouds.png")
和dev.off()
并直接从RStudio保存图,那么我得到:
这也不太好,因为它以某种方式截断了顶部和底部的最后三个子图。
library(ggplot2)
library(ggrepel)
df %>%
filter(book %in% c("Sense & Sensibility", "Pride & Prejudice",
"Mansfield Park", "Emma")) %>%
ggplot(., aes(x = 1, y = 1, size = n, label = word)) +
geom_text_repel(segment.size = 0, segment.alpha = 0) +
scale_size(range = c(2, 15), guide = FALSE) +
theme_void() +
theme(panel.border = element_rect(colour = "black", fill=NA, size=1)) +
facet_wrap(~book) +
labs(title = "Jane Austen Word Clouds")
ggsave("jane_austen_gg.png", width = 11, height = 11)
沿着对角线看起来很奇怪。 wordcloud
看起来更好,因为它也会垂直定位一些单词。
可能没有办法将漂亮的wordcloud
数字插入ggplot吗?
答案 0 :(得分:0)
我相信,使用gridGraphics和gridExtra将图另存为对象会比用排列方式再次绘制更为有用。我已经测试了以下代码,并且可以正常工作。拳头将每个图形保存在不同的对象中,如下所示:
toPlot<-df %>%
filter(book == "Sense & Sensibility")
wordcloud(toPlot$word, toPlot$n, max.words=100, random.order=FALSE, scale=c(3,0.5))
grid.echo()
a <- grid.grab()
#wordcloud2
toPlot2 <- df %>%
filter(book == "Pride & Prejudice")
wordcloud(toPlot2$word, toPlot2$n, max.words=100, random.order=FALSE, scale=c(3,0.5))
grid.echo()
b <- grid.grab()
#wordcloud3
toPlot3 <- df %>%
filter(book == "Mansfield Park")
wordcloud(toPlot3$word, toPlot3$n, max.words=100, random.order=FALSE, scale=c(3,0.5))
grid.echo()
c <- grid.grab()
#wordcloud4
toPlot4 <- df %>%
filter(book == "Emma")
wordcloud(toPlot4$word, toPlot4$n, max.words=100, random.order=FALSE, scale=c(3,0.5))
grid.echo()
d <- grid.grab()
然后,使用4个对象,您可以根据给定的矩阵排列它们。有关布局的更多信息,请参见此:https://cran.r-project.org/web/packages/gridExtra/vignettes/arrangeGrob.html。在以下情况下,第二行中的两个单词云的布局比上方的单词云小:
grid.newpage()
lay <- rbind(c(1,1,1,2,2,2),
c(1,1,1,2,2,2),
c(1,1,1,2,2,2),
c(1,1,1,2,2,2),
c(3,3,3,4,4,4),
c(3,3,3,4,4,4))
grid.arrange(a,b,c,d, layout_matrix = lay)