Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

word-cloud

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.

like image 669
Tavi Avatar asked Dec 25 '22 05:12

Tavi


2 Answers

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

like image 118
Hack-R Avatar answered Mar 08 '23 23:03

Hack-R


Another brilliant solution provided by Victorp in the comments section is to use the following as color argument:

colors=rev(colorRampPalette(brewer.pal(9,"Blues"))(32)[seq(8,32,6)])
like image 45
Tavi Avatar answered Mar 08 '23 23:03

Tavi