2015-06-15 41 views
0

填充值> 0 I有以下幾點:ř多邊形:在密度圖

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) 

我想作的曲線圖,其示出了兩個正常的曲線,其中X> 0具有填充的顏色空間。我嘗試使用polygon但似乎與密度奮鬥(好像用x1[x1>=0]限制了密度函數的數據,我想我需要它來分配第一和然後砍吧)

我想補兩條曲線下的空間,其中X爲零或更大。

enter image description here

回答

1

我設法讓一個相當不雅的解決方案......

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) 

enter image description here