2017-10-05 259 views
0

我有一个介于0和1之间的数字列表,并希望使用scale_color_gradient2提供的算法将它们映射到HEX颜色值。默认颜色值low = muted("red"), mid = "white", high = muted("blue")工作得很好。我需要HEX值本身,而不是在图上着色对象。将值映射到颜色映射颜色

使用matplotlib在Python作为被要求here,但我需要做的这R.

+0

请[提供可再现的示例](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。 – Masoud

+0

如果您提供一个[可重现的示例](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example),那么使用样本输入数据和期望的输出。这样我们可以测试可能的解决方案。 (注意另一个问题给出了样本数据。)回答一个可以推广的具体问题比一个没有具体问题的普通问题更容易。有无数种方法可将0到1之间的数字映射到一个颜色。这是专门关于在'scale_color_gradient2'中复制算法的吗? – MrFlick

回答

2

scale_color_gradient2功能使用着色功能从scales库类似的问题。你可以得到一个转换功能与

library(scales) 
trans <- div_gradient_pal(muted("red"), mid="white", high=muted("blue"), space="Lab") 

然后再应用此功能,您的号码

cols <- trans(seq(0,1, length.out=20)) 
plot(1:20, 1:20, col=cols) 
0

您也可以使用colorRamp功能从基础R的值映射到RGB颜色,然后使用rgb函数转换为十六进制格式。

一个例子:

# I use hex numbers between 0.3 and 0.7 (instead of O and 1) to show that the ggplot scale used the 
# minimum and maximum values by defaults (as done in the python examples you provided) 
set.seed(123) 
d <- data.frame(
    hex = sort(runif(20, 0.3, 0.7)), 
    x = 1:20, 
    y = 1 
) 

# Graph with ggplot and scale_fill_gradient2 
ggplot(d, aes (x, y, fill = hex)) + geom_bar(stat = "identity") + 
    scale_fill_gradient2 (low = "red", mid = "white", high = "blue", midpoint = 0.5) 


# Normalize the vector to use the minimum and maximum values as extreme values 
hexnorm <- (d$hex - min(d$hex))/(max(d$hex) - min(d$hex)) 

# Map the hex values to rgb colors 
mycols <- colorRamp(c("red", "white", "blue"), space = "Lab")(hexnorm) 
# Transform the rgb colors in hexadecimal format 
mycols <- rgb(mycols[,1], mycols[,2], mycols[,3], maxColorValue = 255) 
mycols 

# Check that you obtain the same result as the scale_fill_gradient2 ggplot function 
ggplot(d, aes (x, y)) + geom_bar(stat = "identity", fill = mycols)