r - 根据ggplot2中x和y方向的两个不同变量分配不同的连续颜色渐变
问题描述
我是 R 新手(和堆栈溢出),不胜感激!我无法从其他问题中找到解决方案。我试图:
- 根据不同的变量在 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
解决方案
我在这里尝试了修改 scoa 的答案,也许这可以解决问题。不过,您可能必须手动构建图例,因为这种方法会使默认图例没有吸引力。
使用上面的数据:
df <- data.frame(X = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4),
Y = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4),
V1 = c(256, 4, 196, 16, 144, 36, 100, 64, 81, 49, 121, 25, 169, 9, 225, 1),
V2 = c(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610))
首先,将您的V1
和V2
值缩放为 RGB 颜色的最大 R 和 B 值:
xcol <- df$V1 / max(df$V1)
ycol <- df$V2 / max(df$V2)
现在,使用rgb()
和 缩放值创建一个命名颜色向量:
col <- rgb(ycol, 0, xcol)
names(col) <- as.character(df$V1)
现在您可以绘图,将V1
其作为参数传递给color
参数:
ggplot(df, aes(x = V1, y = V2, color = as.factor(V1))) +
geom_point(size = 5) +
scale_color_manual(values = col) +
theme_classic() +
theme(legend.position = "none")
对于第二个图,保持颜色参数相同:
ggplot(df, aes(x=X, y=Y, color=as.factor(V1))) +
geom_point(size = 5) +
scale_color_manual(values = col) +
theme_classic() +
theme(legend.position = "none")
推荐阅读
- vim - vimscript - 使用自动命令捕捉击键
- c++ - 如何重载运算符>>以输入类的向量值?
- assembly - ARm prfm 和 prfum 指令
- c# - 使用依赖注入 C# 在派生类和基类之间分离日志记录
- elasticsearch - Elasticsearch 字段折叠每个字段值返回 >1 个结果
- spring - 如何访问控制器中的 oauth2 不透明令牌
- java - 将Java时间戳转换为字符串?
- mysql - 选择列包含带有括号和引号的子字符串的位置
- javascript - 本地调用节点后端时,角度http客户端不起作用?
- java - 在没有 Maven 或 Gradle 的情况下为 Spring 应用程序构建一个胖 JAR