【问题标题】:How to shade a graph using curve() in R如何在 R 中使用曲线()对图形进行着色
【发布时间】:2015-03-10 00:55:56
【问题描述】:

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

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

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

【问题讨论】:

标签: r ggplot2 plot graph area


【解决方案1】:

如果你想使用curve和base plot,那么你可以自己写一个小函数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)

【讨论】:

    【解决方案2】:

    我们也可以使用以下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')
    

    【讨论】:

      猜你喜欢
      • 2012-09-07
      • 2012-04-20
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多