如何使用R中的curve()函数为图形添加阴影

4

我正在绘制标准正态分布。

curve(dnorm(x), from=-4, to=4, 
  main = "The Standard Normal Distibution", 
  ylab = "Probability Density",
  xlab = "X")

出于教学目的,我想要阴影化我选择的某个分位数以下的区域。我该如何做?


1
https://dev59.com/Fmcs5IYBdhLWcg3w-Yz4 - Colonel Beauvel
2个回答

6

如果你想使用 curve 和基础绘图,那么你可以使用 polygon 自己编写一个小函数:

colorArea <- function(from, to, density, ..., col="blue", dens=NULL){
    y_seq <- seq(from, to, length.out=500)
    d <- c(0, density(y_seq, ...), 0)
    polygon(c(from, y_seq, to), d, col=col, density=dens)
}

一个小例子如下:
curve(dnorm(x), from=-4, to=4, 
  main = "The Standard Normal Distibution", 
  ylab = "Probability Density",
  xlab = "X")

colorArea(from=-4, to=qnorm(0.025), dnorm)
colorArea(from=qnorm(0.975), to=4, dnorm, mean=0, sd=1, col=2, dens=20)

enter image description here


1
我们也可以使用以下R代码来阴影标准正态曲线在某个(给定的)分位数以下的区域:
library(ggplot2)
z <- seq(-4,4,0.01)
fz <- dnorm(z)
q <- qnorm(0.1) # the quantile
x <- seq(-4, q, 0.01)
y <- c(dnorm(x), 0, 0)
x <- c(x, q, -4)
ggplot() + geom_line(aes(z, fz)) +
           geom_polygon(data = data.frame(x=x, y=y), aes(x, y), fill='blue')

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接