Customised Word Cloud in two different colors in R

与世无争的帅哥 提交于 2021-01-27 21:00:32

问题


I am trying to create a word cloud in R, wherein I have a matrix with positive and negative words, however, I want to show positive and negative words in two different colors (say green and red). Can someone please help me on this. Thanks!

library(qdap)

x1 = x[a0]    

pol = polarity(x1)        
wc = pol$all[,2]          
val = pol$all[,3]         
p  = pol$all[,4]          
n  = pol$all[,5]          

positive_words = unique(setdiff(unlist(p),"-"))  # Positive words list
negative_words = unique(setdiff(unlist(n),"-"))  # Negative words list
total_words1 =cbind(positive_words,negative_words)

pos.tdm = dtm[,which(colnames(dtm) %in% total_words1)]
m = as.matrix(pos.tdm)
v1 = sort(colSums(m), decreasing = TRUE)

windows() # opens new image window
wordcloud(names(v1), v1, scale=c(4,1),1, max.words=100,colors=brewer.pal(8, "Dark2"))
title(sub = "Words - Wordcloud")

回答1:


Yes. You can choose the colors for each word by listing them in colors and then using ordered.colors=TRUE. I am giving a simple example of just red and green words, but you could vary the shades of red and green by the frequency of the word.

Pos = read.table(text="Word    Count
Great       10
Good        25 
Fabulous    7",
header=TRUE, stringsAsFactors = TRUE)

Neg = read.table(text="Word    Count
Bad         23
Stinks      5
Terrible    15",
header=TRUE, stringsAsFactors = TRUE)

AllWords = rbind(Pos, Neg)
Colors = c(rep("green", nrow(Pos)), rep("red", nrow(Neg)))

wordcloud(AllWords $Word, AllWords $Count, 
        colors=Colors, ordered.colors=TRUE)



来源:https://stackoverflow.com/questions/44890569/customised-word-cloud-in-two-different-colors-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!