[英]Wordcloud showing colour based on a variable in R
I'm creating a wordcloud in which the size of the words is based on frequency, but i want the colour of the words to be defined by a variable (a string).我正在创建一个单词云,其中单词的大小基于频率,但我希望单词的颜色由变量(字符串)定义。 The aim is to join two types of a dataset in one wordcloud and to differentiate by color.
目的是在一个词云中加入两种类型的数据集并通过颜色进行区分。 For example, if the type is 'Job' the word appear with the colour blue (#297FD5) and if it's 'Tal' appear with the color grey (#595959).
例如,如果类型为“Job”,则该单词以蓝色显示 (#297FD5),如果为“Tal”,则以灰色显示 (#595959)。
I tried the following, which gave me the colour defined by the code and not what i want.我尝试了以下方法,它给了我代码定义的颜色,而不是我想要的颜色。
AllWords <- data.frame(word = c("Database", "Database", "Javascript","Javascript", "Java", "Java", "CSS", "CSS"),
scale = c(1.007728, 1.111018, 11.892040, 14.085705, 8.031906, 11.009304, 5.026064, 9.257963 ),
type = c("Job", "Tal","Job", "Tal","Job", "Tal","Job", "Tal"),
df_color = c("#297FD5", "#595959","#297FD5", "#595959","#297FD5", "#595959","#297FD5", "#595959"))
#Packages
library(ggwordcloud)
library(ggplot2)
library(dplyr, quietly = TRUE)
library(dplyr, quietly = TRUE, warn.conflicts = FALSE)
library(tidyr, quietly = TRUE)
#Wordcloud
set.seed(42)
ggplot(
AllWords,
aes(
label = word,
size = scale,
color = df_color
)) +
geom_text_wordcloud_area(rm_outside = TRUE, eccentricity = 1) +
scale_size_area(max_size = 10) +
theme_minimal()
Does anyone know how i can change the color for the words depending from a string?有谁知道我如何根据字符串更改单词的颜色? Thanks!
谢谢!
If you want to use the color names or hex codes stored in your column df_color
you have to use scale_color_identity
:如果要使用存储在
df_color
列中的颜色名称或十六进制代码,则必须使用scale_color_identity
:
library(ggwordcloud)
#> Loading required package: ggplot2
library(ggplot2)
set.seed(42)
ggplot(
AllWords,
aes(
label = word,
size = scale,
color = df_color
)) +
geom_text_wordcloud_area(rm_outside = TRUE, eccentricity = 1) +
scale_size_area(max_size = 10) +
scale_color_identity() +
theme_minimal()
I think this may be what you are looking for.我想这可能是你正在寻找的。 Since you are using the
aes
wrapper within ggplot
, you need to color the group by changing color
to what you want the color to be grouped by.由于您在
ggplot
中使用aes
包装器,因此您需要通过将color
更改为您希望颜色分组的颜色来为组着色。 Then you just add scale_color_manual
with the colors you want:然后你只需添加
scale_color_manual
和你想要的 colors :
#Wordcloud
set.seed(42)
ggplot(
AllWords,
aes(
label = word,
size = scale,
color = word,
)) +
geom_text_wordcloud_area(
rm_outside = TRUE,
eccentricity = 1) +
scale_size_area(max_size = 10) +
theme_minimal()+
scale_color_manual(values = c("#297FD5", "red", "#704238", "#A64C93"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.