r - 如何使用 R 为定性渐变着色(使用独立类别/多维度)

标签 r colors ggplot2 gradient colorbrewer

抱歉,如果我遗漏了有关 colorRampPalettebrewer.pal 工作原理的一些基本知识,但是如何基于多个变量创建定性颜色渐变?我的目标是创建一个多维定性梯度,如下图所示(红到绿,红到黄,红到蓝和红到黄到绿- 到蓝色)。

enter image description here

最小的可重现示例:

# example data set
mydata <- 
    data.frame(
        v = runif( 100 ) ,
        w = runif( 100 ) ,
        x = runif( 100 ) ,
        y = runif( 100 ) ,
        z = runif( 100 )
    )
# five columns of random values between zero and one

# use three columns with the `rgb` function to find
# the color between red, green, and blue using all three values
three.dimensions <- rgb( mydata$x , mydata$y , mydata$z )

# between zero and one, this gives black and white
plot( 0:1 , 0:1 , col = rgb( 0:1 , 0:1 , 0:1 ) , pch = 16 , cex = 3 )

# using the three sets of values, color on an rgb gradient
plot( rnorm( 100 ) , rnorm( 100 ) , col = three.dimensions , pch = 16 , cex = 3 )


# how is this multi-dimensionality
# supposed to be implemented in RColorBrewer?
library(RColorBrewer)

# create two colorRampPalette functions,
# for three- and five-category qualitative data
mypal3 <- brewer.pal( 3 , "Set1" )
mypal5 <- brewer.pal( 5 , "Set1" )

crp3 <- colorRampPalette( mypal3 )
crp5 <- colorRampPalette( mypal5 )


# this is just linear..  red, slowly to blue, slowly to green.
plot( rep( 1:10 , 10 ) , rep( 1:10 , each = 10 ) , col = crp3(100)[1:100] , pch = 16 , cex = 3 )

# how would i use RColorBrewer to get a three-way gradient
# with shades between red and green, as opposed to just red-to-blue-to-green?


# this is also linear across five colors.
plot( rep( 1:10 , 10 ) , rep( 1:10 , each = 10 ) , col = crp5(100)[1:100] , pch = 16 , cex = 3 )


# how would i use RColorBrewer to get a five-way gradient
# with shades between
    # red and blue
    # red and green
    # red and purple
    # red and orange
    # and every other combo, depending on the values in `mydata`?

最佳答案

如果我理解这个问题,你想将不同的色阶映射到不同的组。这是一个可能的策略,

x <- seq(0,6*pi-0.01, length=100)
y <- sin(x)
i <- x%/%pi + 1 # groups in the data
d <- data.frame(x=x,y=y,i=i)

cols <- RColorBrewer::brewer.pal(length(unique(i)),"Set1")

library(plyr)

# for each group, map to a specific colorRamp
d2 <- ddply(d, "i", function(.d){
  id <- as.numeric(as.character(unique(.d$i)))
  pal <- colorRamp(c(cols[id], "white"), )
  cols <- pal(scales::rescale(.d$y))
  mutate(.d, col=rgb(cols[,1],cols[,2],cols[,3], maxColorValue = 255))
})


ggplot(d2, aes(x,y,colour=col,group=i))+
  geom_line(lwd=5) + scale_colour_identity() +
  theme_minimal()

同样的想法也适用于 map 。

enter image description here

关于r - 如何使用 R 为定性渐变着色(使用独立类别/多维度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26562926/

相关文章:

r - 沿单一方向延伸 geom_smooth

r - 黄土更平滑的跨度参数的小平面ggplot

r - 我不明白函数内的错误 "object not found"

css - JavaFX:文本区域背景颜色错误

c++ - OpenGL - 着色器中的顶点颜色被交换

r - GGPLOT - 如何根据预定义标签区分线并在 x 轴上添加文本

r - 更改主题后 ggpairs 中的自定义图例消失

r - 将某一行的值与 data.table 中的所有先前行进行比较

r - 查找特定日期属于哪个季节

css - 任何人都可以找出导致我的悬停链接颜色错误的 CSS 吗?