【问题标题】:color a portion of the normal distribution [duplicate]为正态分布的一部分着色[重复]
【发布时间】:2013-05-12 05:22:56
【问题描述】:

我想对正态分布的一部分进行填充或着色。我在这里犯了一个如何做到这一点的例子:

http://msenux.redwoods.edu/math/R/StandardNormal.php

x=seq(-4,4,length=200)
y=dnorm(x)
plot(x,y,type="l", lwd=2, col="blue")
x=seq(-1,1,length=100)
y=dnorm(x)
polygon(c(-1,x,1),c(0,y,0),col="gray")

但是,如果我尝试将上述代码概括为 x 轴的任何部分,我能想到的最好的方法是:

sigma <- 1
mu    <- 0

lower.x <- -0.0
upper.x <-  2.1

x  <- seq(-4, 4, length = 200)
y  <- ( 1/(sigma * sqrt(2*pi)) ) * ( exp(1)^( (-1 * ((x - mu)^2)) / (2*(sigma^2)) ) )
plot(x,y,type="l", lwd=2, col="blue")

x=seq(lower.x, upper.x, length=100)
y  <- ( 1/(sigma * sqrt(2*pi)) ) * ( exp(1)^( (-1 * ((x - mu)^2)) / (2*(sigma^2)) ) )
polygon(c(lower.x,x,1), c(0,y,0), col="gray")

我认为错误涉及第二个长度语句,但我不知道如何纠正错误。另外,我希望正态分布曲线的蓝线不被阴影区域的边界覆盖。虽然这不太重要。谢谢你的建议。

【问题讨论】:

标签: r plot


【解决方案1】:

或多或少来自:http://www.fernandohrosa.com.br/en/P/shaded_areas_in_r/

lower.x <- 0
upper.x <- 2.1
step <- (upper.x - lower.x) / 100
sigma <- 1
mu <- 0
bounds <- c(mu-3*sigma, mu+3*sigma)
cord.x <- c(lower.x,seq(lower.x,upper.x,step),upper.x)
cord.y <- c(0,dnorm(seq(lower.x,upper.x,step),mu,sigma),0)
curve(dnorm(x,mu,sigma),xlim=bounds) 
polygon(cord.x,cord.y,col='skyblue')

另请参阅http://www.r-bloggers.com/functions-for-plotting-and-getting-greek-in-labels/ 并供将来参考: How to shade a region under a curve using ggplot2

【讨论】:

    【解决方案2】:

    下面的代码似乎可以做我想做的事,或者几乎是这样。

    我在下面使用by 语句而不是length 语句。我不确定,但我怀疑x 值的第二个序列必须是x 值的第一个序列的子集。

    然后我重新绘制正态分布曲线以覆盖多边形的顶部灰色边框。我可能想要改进的结果的唯一方面是蓝色在它覆盖灰色的地方有点暗。但在这一点上,这似乎微不足道。

    sigma <- 1
    mu    <- 0
    
    lower.x <- -0.0
    upper.x <-  2.1
    
    x  <- seq(-4, 4, by = 0.1)
    y  <- ( 1/(sigma * sqrt(2*pi)) ) * ( exp(1)^( (-1 * ((x - mu)^2)) / (2*(sigma^2)) ) )
    plot(x,y,type="l", lwd=2, col="blue")
    
    x=seq(lower.x, upper.x, by = 0.1)
    y  <- ( 1/(sigma * sqrt(2*pi)) ) * ( exp(1)^( (-1 * ((x - mu)^2)) / (2*(sigma^2)) ) )
    polygon(c(lower.x,x,upper.x), c(0,y,0), col="gray")
    lines(x, y, col="blue", lwd=2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 2019-01-07
      • 2010-12-30
      • 2020-04-18
      相关资源
      最近更新 更多