lapioche75
lapioche75

Reputation: 97

WordCloud color based on other data column

I'm looking to apply a world cloud function but change the color formatting based on another attribute.

Here is how my data d looks, obviously I have many more city names. The idea is that I would like to have the size of the words based on the number of freq but the colors of the words be based on the 'year' column. This means that paris and nyc would be the same color, and tokyo and rome would have the same color too.

name    freq    year  status
paris   5       2010  booked
nyc     25      2010  booked
tokyo   10      2011  notbooked
rome    9       2011  notbooked

wordcloud(words = d$name, freq = d$freq, min.freq = 1,scale = c(2, 0.2),
                    max.words=200, random.order=FALSE, rot.per=0.1, 
                     colors=brewer.pal(8, "Dark2"))

Howevere for now I dont see how to introduce d$year in the wordcloud function. Thank you in advance for your help!

Upvotes: 2

Views: 3969

Answers (1)

G5W
G5W

Reputation: 37641

Since you say that you wanted tokyo & rome to have the same color, I assume that you meant to have the year for rome to be 2011.

df=read.table(text="name    freq    year
paris   5       2010
nyc     25      2010
tokyo   10      2011
rome    9       2011",
header=TRUE)

library(wordcloud)
wordcloud(words = df$name, freq = df$freq, min.freq = 1,scale = c(2, 0.2),
                    max.words=200, random.order=FALSE, rot.per=0.1, 
                    ordered.colors=TRUE,
                     colors=brewer.pal(8, "Dark2")[factor(df$year)])

Word Cloud

Upvotes: 4

Related Questions