How to make R word cloud display most frequent term in lighter shade of color

Tavi picture Tavi · Aug 26, 2014 · Viewed 8.3k times · Source

I created a word cloud in R with the code:

wordcloud(words$term, words$freq, random.order=FALSE, colors=colorRampPalette(brewer.pal(9,"Blues"))(32), scale=c(5, .5))

And it works fine only that it colors the terms in such a way that the most frequent appear in the darkest shade of the color and the least frequent in the lightest shade of the color. But I want it to be the other way round. Any pointers? Thanks.

Answer

Hack-R picture Hack-R · Aug 26, 2014

Good question. You can specify non-random color assignment (random.color = FALSE) which will make it based on frequency then choose a value of colors using a palette that goes in the order you prefer.

For example, if colors = "black", which is the default/example in the Vignette is the opposite of what you want, then choose colors = "Pastel" or some other scale that you prefer.

Personally, I use Color Brewer (RColorBrewer) with a sequential pallete to accomplish this:

pal = brewer.pal(9,"Blues")
wordcloud(words = d$word, 
          freq = d$freq, 
          scale = c(8,.3), 
          random.order = F,
          random.color = F,
          colors = pal) 

Alternately, you could use rev on your color pallet, as @Victorp pointed out in the comments. Here's an example of that:

pal = brewer.pal(9,"BuGn")
wordcloud(words = d$word, 
          freq = d$freq, 
          scale = c(8,.3), 
          random.order = F,
          random.color = F,
          colors = rev(pal))    

which gives you something like this:

Word Cloud

Update: I've written a blog article that covers this topic as well as the n-gram case and scraping data for your word clouds: http://hack-r.com/?p=35