我有一个介于0和1之间的数字列表,并希望使用scale_color_gradient2
提供的算法将它们映射到HEX颜色值。 low = muted("red"), mid = "white", high = muted("blue")
的默认颜色值可以正常工作。我需要HEX值而不是在绘图上着色对象。
在python中使用matplotlib的类似问题被问到here,但我需要在R中执行此操作。
答案 0 :(得分: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)
答案 1 :(得分:0)
您还可以使用基础R中的colorRamp
函数将值映射到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)