在ggplot中按类别指定不同的颜色渐变

时间:2017-09-01 23:29:43

标签: r ggplot2

我有一个与模拟波纹管结构相似的数据集:

dat <- data.frame(x=runif(1000,-10,10),y=runif(1000,-10,10))

我创建了一列来通知X和Y高于/低于零的象限:

dat$cond <- NA
dat$cond[which(dat$x>0 & dat$y>0)] <- "HH"
dat$cond[which(dat$x>0 & dat$y<0)] <- "HL"
dat$cond[which(dat$x<0 & dat$y<0)] <- "LL"
dat$cond[which(dat$x<0 & dat$y>0)] <- "LH"

我绘制了这些数据,以便为每个象限获得不同的颜色:

ggplot(dat, aes(x, y, color=cond)) +
geom_point(size=2, show.legend = FALSE) +
theme_classic() +
theme(text = element_text(colour="black", size = 26), aspect.ratio=1) + 
geom_hline(yintercept=0,color="gray20",linetype=2) +
geom_vline(xintercept=0,color="gray20",linetype=2) + 
scale_color_manual(values=c("red","blue", "orange","green"))

我需要使用相同的颜色,但渐变范围从白色更接近零到暗色除零。

1 个答案:

答案 0 :(得分:0)

也许这是一个解决方案,但您可以使用alpha审美和一些自定义索引来实现您所描述的效果。这是一个简短的例子(你可以调整索引生成函数来影响alpha):

library(ggplot2)
dat <- data.frame(x = runif(1000, -10, 10), y = runif(1000, -10, 10))

dat$cond <- NA
dat$cond[which(dat$x > 0 & dat$y > 0)] <- "HH"
dat$cond[which(dat$x > 0 & dat$y < 0)] <- "HL"
dat$cond[which(dat$x < 0 & dat$y < 0)] <- "LL"
dat$cond[which(dat$x < 0 & dat$y > 0)] <- "LH"
dat$alpha_idx <- (abs(dat$x) + abs(dat$y))/2

ggplot(dat, aes(x, y, color = cond)) +
  geom_point(aes(alpha = alpha_idx), size = 2, show.legend = FALSE) +
  geom_hline(yintercept = 0, color = "gray20", linetype = 2) +
  geom_vline(xintercept = 0, color = "gray20", linetype = 2) +
  scale_color_manual(values = c("red", "blue", "orange", "green")) +
  theme_classic() +
  theme(text = element_text(colour = "black", size = 26), aspect.ratio = 1)