在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)为名称着色,还是应该使用不同的软件/包?
答案 0 :(得分:3)
如果指定了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)
如果你只有因子而不是颜色列表,你可以生成一个带有几行的并行colorlist
。
#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)) ]