简体   繁体   English

硬编码十六进制字符串值作为ggplot中的颜色

[英]Hardcode hexadecimal string values as color in ggplot

I have a data frame with "x" and "y" columns as numeric values, and a third column "cluster" as a hexidecimal string, an example seen below: 我有一个数据框,其中“ x”和“ y”列为数值,第三列“ cluster”为十六进制字符串,如下所示:

library(ggplot2)
library(scales)
colList = c(scales::hue_pal()(3),"#520090")
dat = data.frame(x=runif(100,0,1),y=runif(100,0,1),cluster=sample(1:4, 100, replace=T))
dat$cluster = factor(dat$cluster)
levels(dat$cluster) = c(colList)
head(dat)

I am trying to create a scatterplot with "x" and "y" columns mapped to the x and y axis, and with those points colored according to the hexadecimal value stored in the "cluster" column. 我正在尝试创建一个散点图,将“ x”和“ y”列映射到x和y轴,并根据存储在“簇”列中的十六进制值对这些点进行着色。 I have tried the following: 我尝试了以下方法:

ggplot(dat,aes(x,y))+ geom_point(aes(colour = cluster), alpha=0.5)

However, this simply assigns the default first four values stored in scales::hue_pal()(4), and I have changed the last one to a dark purple color with hexadecimal value #520090. 但是,这只是分配存储在scales :: hue_pal()(4)中的默认前四个值,而我将最后一个更改为十六进制值#520090的深紫色。 I also am trying to change the default hexadecimal values from appearing as the text in the legend. 我还试图更改默认的十六进制值,使其不显示为图例中的文本。 I tried unsuccessfully to hardcode in "Cluster 1", "Cluster 2", ..., "Cluster 4" as the legend text: 我尝试在“ Cluster 1”,“ Cluster 2”,...,“ Cluster 4”中将图例文本硬编码为失败:

ggplot(dat,aes(x,y))+ geom_point(aes(colour = cluster), alpha=0.5) + theme(legend.text = element_text("Cluster 1","Cluster 2","Cluster 3","Cluster 4"))

Any advice is much appreciated! 任何建议深表感谢!

In order to color the dots based on the cluster identity, the cluster name (ie, your hex values) needd to be mapped to a set of aesthetic values. 为了根据聚类标识为点着色,聚类名称(即您的十六进制值)需要映射到一组美学值。

Since you want to have the hex values from the cluster column to represent actual colors, you can use the scale_color_manual function and give the levels of the cluster column as the values parameter. 由于要使簇列中的十六进制值代表实际颜色,因此可以使用scale_color_manual函数并将簇列的级别作为values参数。 To changes the labels, simply set the desired labels value. 要更改标签,只需设置所需的标签值。

ggplot(dat, aes(x,y)) + geom_point(aes(colour = cluster), alpha=0.5) +
scale_color_manual(values = levels(dat$cluster), 
                   labels = c("Cluster1","Cluster2","Cluster3", "Cluster4"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM