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):
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.
Result