Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

plot - Shaded area under two curves using R

I wrote the following code in R

x=seq(-7,10,length=200)
y1=dnorm(x,mean=0,sd=1)
plot(x,y1,type="l",lwd=2,col="red")
y2=dnorm(x,mean=3,sd=2)
lines(x,y2,type="l",lwd=2,col="blue")

How can I shade the area under both curves (known as the overlap between the two curves).

I will highly appreciate any suggestions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Oh, well, @SachaEpskamp beat me to it, but here is my much less elegant solution.

shade_under_curve <- function(fun, xmin, xmax, length=100){
  xvals <- seq(xmin, xmax, length=length)
  dvals <- match.fun(fun)(xvals)
  polygon(c(xvals,rev(xvals)),c(rep(0,length),rev(dvals)),col="gray")
}


y1 <- function(x)sapply(x, function(xt)dnorm(xt,mean=0,sd=1))
y2 <- function(x)sapply(x, function(xt)dnorm(xt,mean=3,sd=2))

my.fun <- function(x){sapply(x, function(xt)min(y1(xt), y2(xt)))}

Edit to include initial plot:

plot(y1, -10, 10, col="red")
curve(y2, add=TRUE, col="blue")
shade_under_curve(my.fun, -10, 10, length=1000)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...