如何分割多边形并沿偏斜值填充区域?

How to split a polygon and fill areas along skew values?

如果值非常简单,我知道如何沿水平线分割和填充多边形区域。

x <- 9:15
y1 <- c(5, 6, 5, 4, 5, 6, 5)

plot(x, y1, type="l")
abline(h=5, col="red", lty=2)

polygon(x[c(1:3, 5:7)], y1[c(1:3, 5:7)], col="green")
polygon(x[3:5], y1[3:5], col="red")

y2 <- c(5, 6, 4, 7, 5, 6, 5)

plot(x, y2, type="l")
abline(h=5, col="red", lty=2)

但是如果值有点偏斜,如何得到结果呢?

预期输出(照片处理):

正如@Henrik 在评论中指出的那样,我们可以 interpolate the missing points

如果数据以另一个非零值为中心——就像我的情况——我们需要稍微调整一下方法。

x <- 9:15
y2 <- c(5, 6, 4, 7, 5, 6, 5)

zp <- 5  # zero point
d <- data.frame(x, y=y2 - zp)              # scale at zero point

# kohske's method
new_d <- do.call(rbind, 
                 sapply(1:(nrow(d) - 1), function(i) {
                   f <- lm(x ~ y, d[i:(i + 1), ])
                   if (f$qr$rank < 2) return(NULL)
                   r <- predict(f, newdata=data.frame(y=0))
                   if(d[i, ]$x < r & r < d[i + 1, ]$x)
                     return(data.frame(x=r, y=0))
                   else return(NULL)
                 })
)

d2 <- rbind(d, new_d)
d2 <- transform(d2, y=y + zp)              # descale
d2 <- unique(round(d2[order(d2$x), ], 4))  # get rid of duplicates

# plot
plot(d2, type="l")
abline(h=5, col="red", lty=2)

polygon(d2$x[c(1:3, 5:9)], d2$y[c(1:3, 5:9)], col="green")
polygon(d2$x[3:5], d2$y[3:5], col="red")

结果