如何使用polygon()在概率密度曲线下方着色

Joh*_*ohn 5 plot r

我无法在分布下方polygon()一直阴影到x轴.它似乎高于指数分布到一条线.这是我到目前为止的地方:y=-x

x <- seq(0,50,0.01)
y <- dexp(seq(0,50,0.01),rate=0.11)
plot(x, y, type="l", col=col2rgb("yellow",0.5), xaxs="i", yaxs="i", ylim=c(0,0.15))
polygon(x, y ,border=NA,col=col2rgb("yellow",0.5))
Run Code Online (Sandbox Code Playgroud)

阴凉处

非常感谢!

李哲源*_*李哲源 8

通过添加(0,0)到多边形的顶点,解决方案很简单.见下文:

x <- seq(0,50,0.01)
y <- dexp(seq(0,50,0.01),rate=0.11)
plot(x, y, type="l", col=col2rgb("yellow",0.5), xaxs="i", yaxs="i", ylim=c(0,0.15))
polygon(c(0, x), c(0, y), border=NA, col=col2rgb("yellow",0.5))
Run Code Online (Sandbox Code Playgroud)

阴凉处


怎么polygon()工作

polygon()将按顺序排列所有顶点.原始代码的问题是原点(0, 0)不是顶点之一,因此它不是多边形的一部分.您还可以考虑以下玩具示例:

x0 <- c(0, 0.5, 1.5)
y0 <- c(1.5, 0.5, 0)
## triangle, with three vertices
plot(x0, y0, pch = ".")
polygon(x0, y0, col = "red", border = NA)
## area under triangle, four vertices
polygon(c(0, x0), c(0, y0), col = "yellow", border = NA)
Run Code Online (Sandbox Code Playgroud)

玩具的例子