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

时间:2019-01-29 17:27:33

标签: r plot polygon

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

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")

enter image description here

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

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

但是,如果值偏斜些,如何获得结果呢?

预期产量(已购物):

enter image description here

1 个答案:

答案 0 :(得分:0)

@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")

结果 enter image description here