您在这里至少有几个选择。第一个非常简单、通用(因为它不限于直线段)和精确,但使用基础plot 而不是ggplot。第二个使用ggplot,但稍微复杂一些,颜色转换不会100%精确(但足够接近,只要您指定适当的分辨率...继续阅读)。
基地:
如果您愿意使用base 绘图函数而不是ggplot,您可以将绘图区域剪切到阈值(2.2)以上,然后以您喜欢的颜色绘制线段,然后剪切到该区域低于阈值,并再次绘制为红色。虽然第一个剪辑完全没有必要,但它可以防止过度绘制不同的颜色,这可能看起来有点暗淡。
threshold <- 2.2
set.seed(123)
stackOne=data.frame(id=rep(c(1,2,3),each=3),
y=rnorm(9,2,1),
x=rep(c(1,2,3),3))
# create a second df to hold segment data
d <- stackOne
d$y2 <- c(d$y[-1], NA)
d$x2 <- c(d$x[-1], NA)
d <- d[-findInterval(unique(d$id), d$id), ] # remove last row for each group
plot(stackOne[, 3:2], pch=20)
# clip to region above the threshold
clip(min(stackOne$x), max(stackOne$x), threshold, max(stackOne$y))
segments(d$x, d$y, d$x2, d$y2, lwd=2)
# clip to region below the threshold
clip(min(stackOne$x), max(stackOne$x), min(stackOne$y), threshold)
segments(d$x, d$y, d$x2, d$y2, lwd=2, col='red')
points(stackOne[, 3:2], pch=20) # plot points again so they lie over lines
ggplot:
如果您想或需要使用ggplot,可以考虑以下...
一种解决方案是使用geom_line(aes(group=id, color = y < 2.2)),但是这将根据每个段开始处的点的 y 值分配颜色。我相信您不仅希望在节点处进行颜色更改,还希望在一条线越过您给定的 2.2 阈值的任何地方进行颜色更改。我对 ggplot 不是很熟悉,但实现这一点的一种方法是通过沿着连接现有点的线创建新点来制作数据的更高分辨率版本,然后使用 color = y < 2.2 参数来实现想要的效果。
例如:
threshold <- 2.2 # set colour-transition threshold
yres <- 0.01 # y-resolution (accuracy of colour change location)
d <- stackOne # for code simplification
# new cols for point coordinates of line end
d$y2 <- c(d$y[-1], NA)
d$x2 <- c(d$x[-1], NA)
d <- d[-findInterval(unique(d$id), d$id), ] # remove last row for each group
# new high-resolution y coordinates between each pair within each group
y.new <- apply(d, 1, function(x) {
seq(x['y'], x['y2'], yres*sign(x['y2'] - x['y']))
})
d$len <- sapply(y.new, length) # length of each series of points
# new high-resolution x coordinates corresponding with new y-coords
x.new <- apply(d, 1, function(x) {
seq(x['x'], x['x2'], length.out=x['len'])
})
id <- rep(seq_along(y.new), d$len) # new group id vector
y.new <- unlist(y.new)
x.new <- unlist(x.new)
d.new <- data.frame(id=id, x=x.new, y=y.new)
p <- ggplot(d.new, aes(x=x,y=y)) +
geom_line(aes(group=d.new$id, color=d.new$y < threshold))+
geom_point(data=stackOne)+
scale_color_discrete(sprintf('Below %s', threshold))
p
很可能有一种方法可以通过 ggplot 函数来做到这一点,但同时我希望这会有所帮助。我不知道如何将ggplotGrob 绘制成剪裁的viewport(它似乎只是缩放情节)。如果您希望颜色以某个 x 值阈值为条件,这显然需要一些调整。