我已经能够找到other问题的解决方案了 . 我试着:
-
根据不同的变量在x和y方向分配2个不同的连续色彩渐变 . (下面的代码中的plot1)
-
为同一数据框的不同变量的不同图保留这些颜色分配 . (下面的代码中的plot2)
我只能根据一个变量管理分配颜色,如下所示 .
例:
####set up data####
#using ggplot2 package
library(ggplot2)
df <- data.frame(c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4),
c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4),
c(256, 4, 196, 16, 144, 36, 100, 64, 81, 49, 121, 25, 169, 9, 225, 1),
c(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610))
colnames(df) <- c("X", "Y", "V1", "V2")
####plot1: Simple plot of V1 vs V2#####
#I would like the color to go towards blue as V1 increases on x axis (as it is now)
#I would also like the color to go towards red as V2 increases on y axis
#Ideally, when both x and y are large, it would be some purple color
plot1 <- ggplot(df, aes(x=V1, y = V2, color= V1)) + geom_point()+
scale_color_continuous(low="black", high="light blue")+
labs(y= "V2: I want this to go from black --> red", x = "V1: black--> blue")
plot1
####plot2: plot of x vs y but with color assignment same as plot1####
#The position based on X and Y is correct but,
# I'd like to have the color assigned based on V1 and V2 (same as plot1)
plot2 <- ggplot(df, aes(x=X, y=Y, color=V1)) + geom_point()+
scale_color_continuous(low="black", high="light blue")
plot2
1 回答
我've tried a modification scoa' s answer here,也许这样就可以了 . 您可能必须手动构建图例,因为这种方法使默认图例没有吸引力 .
根据您的数据:
首先,将
V1
和V2
值缩放为RGB颜色的最大R和B值:现在,使用
rgb()
和缩放值创建一个命名颜色向量:现在你可以绘制,将
V1
作为因子传递给color
参数:对于第二个图,保持颜色参数相同: