问题
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")
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):
回答1:
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
来源:https://stackoverflow.com/questions/54426523/how-to-split-a-polygon-and-fill-areas-along-skew-values