问题
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