在 R 中叠加两个面积绘图仪函数

问题描述 投票:0回答:1

我有一个函数设置来绘制高斯分布曲线下的面积,我希望能够突出显示同一图上的两个区域。在这种情况下,应该对其进行镜像。

areaplotter <- function(x1,x2){
  x <- seq(from=-4,to=4,len=100)
  plot(x,dnorm(x),type='l')
  jj <- seq(from=x1,to=x2,len=100)
  polygon(x=c(jj,x2,x1),y=c(dnorm(jj),0,0),col='red')
}

本质上我想将以下两个图合二为一

areaplotter(-4,qnorm(0.05))
areaplotter(qnorm(1-0.05),4)

现在我设法将它们放在一起

par(mfrow = c(1,2))
但我希望阴影区域出现在一个图上

是否有简单的语法或者我应该使用其他函数? 预先感谢。

我尝试使用

lines()
函数,但我是 R 新手,它不起作用,所以我可能做错了

r plot
1个回答
0
投票

我简化了函数,使其只需要 alpha 级别。

areaplotter <- function(alpha = 0.05){
  x <- seq(from=-4,to=4,len=100)
  plot(x, dnorm(x), type='l')
  
  x1 <- qnorm(alpha)
  x2 <- qnorm(1 - alpha)
  jj1 <- seq(from = x[1], to = x1, len=100)
  jj2 <- seq(from = x2, to = x[100], len=100)
  polygon(x = c(jj1, x1, x[1]), y=c(dnorm(jj1), 0, 0), col = 'red')
  polygon(x = c(jj2, x[100], x2), y=c(dnorm(jj2), 0, 0), col = 'red')
}

areaplotter()

areaplotter(0.1)

© www.soinside.com 2019 - 2024. All rights reserved.