R多边形:密度图中的填充值> 0

R polygon: fill values >0 in a density plot

我有以下内容:

set.seed(513)
x1 = rnorm(12^6, 5,5)
x2 = x1-10
plot(density(x1),xlim = c(-25,25), ylim = c(0,0.09), xaxs = "i", yaxs = "i", main ="", xaxt = "n", yaxt = "n", xlab = "", ylab = "", col = "blue")
lines(density(x2), col = "red")
axis(side = 1, pos = 0, at = c(-30,-20,-10,0,10,20,30), labels = c("",-2,-1,0,+1,+2,""), tck = -0.02)
lines(x=c(0,0),y=c(0,1), lty = 3)
polygon(density(x1[x1>=0]), col = rgb(0,0,0.5,0.5))
polygon(density(x2[(x2)>=0]), col = rgb(0.5,0,0,0.5))
par(xpd=TRUE)
text("Frequency", x = -29, y = 0.045, srt = 90)
par(xpd=FALSE)

我想制作一个显示两条正态曲线的图,space 其中 X>0 具有填充颜色。我尝试使用 polygon 但它似乎与密度有关(似乎使用 x1[x1>=0] 将密度函数限制为该数据,我想我需要它首先进行分布然后 然后 剪掉它)

我想在 X 为零或更大的两条线的曲线下方填充 space。

我设法做出了一个相当不优雅的解决方案...

set.seed(513)
x1 = rnorm(12^6, 5,5)
x2 = x1-10
plot(density(x1),xlim = c(-25,25), ylim = c(0,0.09), xaxs = "i", yaxs = "i", main ="", xaxt = "n", yaxt = "n", xlab = "", ylab = "", col = "blue")
lines(density(x2), col = "red")
axis(side = 1, pos = 0, at = c(-30,-20,-10,0,10,20,30), labels = c("",-2,-1,0,+1,+2,""), tck = -0.02)
lines(x=c(0,0),y=c(0,1), lty = 3)

x = density(x1)[1]
y = density(x1)[2]
x = as.numeric(x[[1]])
y = as.numeric(y[[1]])
df = data.frame(x,y)
polygon(c(df$x[df$x>=0],0),c(df$y[df$x>=0],0),col = rgb(0,0,0.5,0.5))
x = density(x2)[1]
y = density(x2)[2]
x = as.numeric(x[[1]])
y = as.numeric(y[[1]])
df = data.frame(x,y)
polygon(c(df$x[df$x>=0],0),c(df$y[df$x>=0],0),col = rgb(0.5,0,0,0.5))

par(xpd=TRUE)
text("Frequency", x = -29, y = 0.045, srt = 90)
par(xpd=FALSE)