首先绘制密度函数,然后调用polygon函数为区域填充阴影来创建图。函数polygon会绘制一连串线围绕明亮区域并填充他。
首先,绘制密度图,以正态分布为例:
x <- seq(from = -5, to = +5, length.out = 100) y <- dnorm(x) plot(x, y, main = "Standard Normal Distribution", type = "l", ylab = "Density", xlab = "Quantile") abline(h = 0)然后,用一系列线段来填充感兴趣区域(填充阴影)。这些线段依次由一系列(x,y)坐标定义。函数polygon会连接第一个和最后一个(x,y)坐标来闭合这个多边形,如下:
region.x <- x[0 <= x & x <= 4] region.y <- y[0 <= x & x <= 4] region.x <- c(region.x[1], region.x, tail(region.x, 1)) region.y <- c(0, region.y, 0) polygon(region.x, region.y, density = 10) ### 默认density=10, 表示以倾斜45度的细线来填充结果如下: 当然也可以用颜色来填充,只需将density设置为-1, 并且将col设置为喜欢颜色即可:
polygon(region.x, region.y, density = -1, col = "blue")