r - 如何在 R 中使用曲线()对图形进行着色

标签 r ggplot2 plot graph area

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

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

出于教学原因,我想将低于我选择的某个分位数的区域涂上阴影。我怎样才能做到这一点?

最佳答案

如果您想使用 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

关于r - 如何在 R 中使用曲线()对图形进行着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27898931/

相关文章:

R:如何画一 strip 有多个箭头的线?

r - 杀死所有挂起时间超过一分钟的 R 进程

r - 如何将散点图中每个点的垂线下降到(特征)向量?

linux - Octave 保存为未定义

python - Matplotlib 中的非线性第二轴

r - x 和 y 变量来自不同的数据框(ggplot2)

r - R中可变数量的for循环

r - 如何向量化多参数下的似然计算?

r - 删除*所有*重复的行,除非有 “similar”行

r - 在密度分布顶部绘制中值