I'm trying to make subplots/facets of several wordclouds in a way that's pleasing to the eye.
Problems:
- I can't get base R to combine
wordcloud
-outputs properly - making wordclouds with
ggplot2
allows for facetting but yields unsatisfactory results (ugly positioning)
I've tried to two ways to create these wordcloud-subplots.
1. I create an example dataset (following here):
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)
2. My first try uses the wordcloud
package and base 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()
Creating:
So somehow it only saves the last subplot. If I don't use png("jane_austen_wordclouds.png")
and dev.off()
and just save the figure straight from RStudio, then I get:
That's also not nice, as it somehow truncates the last three subplots at the top and bottom.
3. Second, I use ggplot (inspired by this):
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)
That looks strangely drawn out along the diagonal. And wordcloud
looks better as it also orients some of the words vertically.
Might there not be a way to insert the pretty wordcloud
figures into ggplot?