2016-01-29 161 views
3

這裏的問題是:如何填充R中某些特定區域的顏色?

x<-seq(0,10,length.out = 1000) 
y1<-dnorm(x,mean = 2,sd=1) 
y2<-dnorm(x,mean = 6,sd=1) 
plot(x,y1,type="l") 
lines(x,y2) 
abline(v=x[380]) 

圖表如下所示。如何在垂直線的兩側填充2種不同的顏色,例如紅色和藍色,但仍低於兩個正常密度函數。我以爲我可以使用多邊形,但失敗了。

這是無填充顏色的圖形:

enter image description here

+0

你想填補了兩個密度的最大值以下,或者你想兩個密度填充不同的顏色(也許有的透明度,使你可以看到重疊)下的面積? – Gregor

+0

@Gregor一個是垂直線右側的部分,但低於左側法線密度的右側尾部,另一個是右側法線密度左側但低於左側尾部的部分。對不起,措辭嚴重........ –

+0

不用擔心, - 所以在任何'x'點,你只想填補最低密度 - 或者說另一種方式,你想填補交叉/重疊的密度。 (垂直線任一側的不同顏色都非常清晰。) – Gregor

回答

3

這裏有一種方法:

首先,我們會得到你的密度的並行最低 - 這是對一個向量頂部y我們的多邊形座標。

y = pmin(y1, y2) 

# set up your plot as in the question  
plot(x, y1, type="l") 
lines(x, y2) 

# define a re-usable variable for the vertical line placement 
x_vert = 380 
abline(v = x[x_vert]) 

# Now we'll draw 2 polygons, one for the left side, one for the right. 
# The first (x,y) pairs of the polygon are just the (x,y) coords of the 
# density we're filling to, until the vertical line 
# Then we need to connect the "bottom" points, which have coordinates 
# (x[x_vert], 0) and (x[1], 0)  
polygon(x = c(x[1:x_vert], x[x_vert], x[1]), 
     y = c(y[1:x_vert], 0, 0), 
     col = "blue") 
# similar for the right hand polygon, but now going from x_vert to length(x) 
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") 

瞧!

enter image description here

+0

酷,thx無論如何! –