Here is one way:
First, we get a parallel minimum of your densities - this is the vector of upper coordinates yfor our polygons.
y = pmin(y1, y2)
plot(x, y1, type="l")
lines(x, y2)
x_vert = 380
abline(v = x[x_vert])
polygon(x = c(x[1:x_vert], x[x_vert], x[1]),
y = c(y[1:x_vert], 0, 0),
col = "blue")
polygon(x = c(x[x_vert:length(x)], x[length(x)], x[x_vert]),
y = c(y[x_vert:length(x)], 0, 0),
col = "red")
Voila!

source
share