使用R的两条曲线下的阴影区域 [英] Shaded area under two curves using R

查看:283
本文介绍了使用R的两条曲线下的阴影区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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.

推荐答案

哦,@ SachaEpskamp击败了我,但这是我不太优雅的解决方案.

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)))}

编辑以包括初始图:

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

这篇关于使用R的两条曲线下的阴影区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆