2017-10-05 146 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)