How to split a polygon and fill areas along skew v

2019-07-28 18:49发布

I know how to split and fill areas of a polygon along a horizontal line, if the values are quite simple.

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)

But how to get the result if the values are a bit more skew?

Expected output (photoshopped):

enter image description here

标签: r plot polygon
1条回答
小情绪 Triste *
2楼-- · 2019-07-28 19:15

As pointed out by @Henrik in comments we can interpolate the missing points.

If the data is centered around another value than zero – as in my case – we need to adapt the method a little.

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

Result enter image description here

查看更多
登录 后发表回答