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

问题描述

我用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 的两条曲线下的阴影区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:31