使用 R 中的 wordcloud 包,我想根据数据集中的分类变量为不同的单词着色。假设我的数据如下:
name weight group
1 Aba 10 x
2 Bcd 20 y
3 Cde 30 z
4 Def 5 x
这里作为dput
:
dat <- structure(list(name = c("Aba", "Bcd", "Cde", "Def"), weight = c(10,
20, 30, 5), group= c("x", "y", "z", "x")), .Names = c("name",
"weight", "group"), row.names = c(NA, -4L), class = "data.frame")
wordcloud() 中有没有办法按组(x、y、z)为名称着色,或者我应该使用不同的软件/软件包?
最佳答案
如果指定了 ordered.colors
,它将根据频率或词序自动从颜色列表中进行选择。
name = c("Aba","Bcd","Cde","Def")
weight = c(10,20,30,5)
colorlist = c("red","blue","green","red")
wordcloud(name, weight, colors=colorlist, ordered.colors=TRUE)
上面的示例适用于自变量。在数据框中,您的颜色规范将存储为一个因素,并且必须通过将其包装在 as.character
中将其转换为文本,如下所示:
wordcloud(df$name, df$weight, colors=as.character(df$color), ordered.colors=TRUE)
如果您只有因子而不是颜色列表,则可以使用几行生成并行颜色列表
。
#general solution for any number of categories
basecolors = rainbow(length(unique(group)))
# solution for known categories
basecolors = c("red","green","blue")
group = c("x","y","z","x")
# find position of group in list of groups, and select that matching color...
colorlist = basecolors[ match(group,unique(group)) ]
关于r - r wordclouds 中的彩色类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18902485/