How to Generate Word Clouds in R. Simple Steps on How and When to Use... | by Céline Van den Rul | Towards Data Science

In the following section, I show you 4 simple steps to follow if you want to generate a word cloud with R.
To generate word clouds, you need to download the wordcloud package in R as well as the RcolorBrewer package for the colours. Note that there is also a wordcloud2 package, with a slightly different design and fun applications. I will show you how to use both packages.
install.packages("wordcloud")library(wordcloud)install.packages("RColorBrewer")library(RColorBrewer)install.packages("wordcloud2)library(wordcloud2)
Most often, word clouds are used to analyse twitter data or a corpus of text. If you’re analysing twitter data, simply upload your data by using the rtweet package (see this article for more info on this). If you’re working on a speech, article or any other type of text, make sure to load your text data as a corpus. A useful way to do this is to use the tm package.
install.packages("tm")library(tm)#Create a vector containing only the texttext <- data$text# Create a corpus  docs <- Corpus(VectorSource(text))
Cleaning is an essential step to take before you generate your wordcloud. Indeed, for your analysis to bring useful insights, you may want to remove special characters, numbers or punctuation from your text. In addition, you should remove common stop words in order to produce meaningful results and avoid the most common frequent words such as “I” or “the” to appear in the word cloud.
If you’re working with tweets, use the following line of code to clean your text.
gsub("https\\S*", "", tweets$text) gsub("@\\S*", "", tweets$text) gsub("amp", "", tweets$text) gsub("[\r\n]", "", tweets$text)gsub("[[:punct:]]", "", data$text)
If you’re working with a corpus, there are several packages you can use to clean your text. The following lines of code show you how to do this using the tm package.
docs <- docs %>%  tm_map(removeNumbers) %>%  tm_map(removePunctuation) %>%  tm_map(stripWhitespace)docs <- tm_map(docs, content_transformer(tolower))docs <- tm_map(docs, removeWords, stopwords("english"))
What you want to do as a next step is to have a dataframe containing each word in your first column and their frequency in the second column.
This can be done by creating a document term matrix with the TermDocumentMatrix function from the tm package.
dtm <- TermDocumentMatrix(docs) matrix <- as.matrix(dtm) words <- sort(rowSums(matrix),decreasing=TRUE) df <- data.frame(word = names(words),freq=words)
Alternatively, and especially if you’re using tweets, you can use the tidytext package.
tweets_words <-  tweets %>% select(text) %>% unnest_tokens(word, text)words <- tweets_words %>% count(word, sort=TRUE)
The wordcloud package is the most classic way to generate a word cloud. The following line of code shows you how to properly set the arguments. As an example, I chose to work with the speeches given by US Presidents at the United Nations General Assembly.
set.seed(1234) # for reproducibility wordcloud(words = df$word, freq = df$freq, min.freq = 1,           max.words=200, random.order=FALSE, rot.per=0.35,            colors=brewer.pal(8, "Dark2"))
It may happen that your word cloud crops certain words or simply doesn’t show them. If this happens, make sure to add the argument scale=c(3.5,0.25) and play around with the numbers to make the word cloud fit.
Another common mistake with word clouds is to show too many words that have little frequency. If this is the case, make sure to adjust the minimum frequency argument (min.freq=...) in order to render your word cloud more meaningful.
The wordcloud2 package is a bit more fun to use, allowing us to do some more advanced visualisations. For instance, you can choose your wordcloud to appear in a specific shape or even letter (see this vignette for a useful tutorial). As an example, I used the same corpus of UN speeches and generated the two word clouds shown below. Cool, right?
wordcloud2(data=df, size=1.6, color='random-dark')
wordcloud2(data=df, size = 0.7, shape = 'pentagon')
Word clouds are killer visualisation tools. They present text data in a simple and clear format, that of a cloud in which the size of the words depends on their respective frequencies. As such, they are visually nice to look at as well as easy and quick to understand.
Word clouds are great communication tools. They are incredibly handy for anyone wishing to communicate a basic insight based on text data — whether it’s to analyse a speech, capture the conversation on social media or report on customer reviews.
Word clouds are insightful. Visually engaging, word clouds allow us to draw several insights quickly, allowing for some flexibility in their interpretation. Their visual format stimulates us to think and draw the best insight depending on what we wish to analyse.
Yes, word clouds are insightful, great communication and visualisation tools. Nonetheless, they also have their limits and understanding this is key to know when to use them and therefore also when not to.
Word clouds are essentially a descriptive tool. They should therefore only be used to capture basic qualitative insights. Visually attractive, they are a great tool to start a conversation, a presentation or an analysis. However, their analysis is limited to insights that simply don’t have the same calibre as more extensive statistical analysis.
I regularly write articles about Data Science and Natural Language Processing. Follow me on Twitter or Medium to check out more articles like these or simply to keep updated about the next ones. Thanks for reading!