如何绘制标准正态分布-2.25<Z<1.77区间的曲线下面积图?
Got it, I totally get what you're trying to do—plotting the area under the standard normal curve between z = -2.25 and z = 1.77 with vertical lines marking those bounds. The mosaic::xpnorm() function is great for single z-values, but it doesn't have a built-in argument for interval areas directly. Let's cover a couple of solid ways to pull this off:
方法1:用mosaic包叠加绘制(适配你已有的工具)
You can hack xpnorm() by layering two plots: first draw the area up to z=1.77, then cover the area left of z=-2.25 with a white fill. This leaves exactly the interval area you want visible:
library(mosaic) # 先绘制z=1.77左侧的全部面积(蓝色填充) xpnorm(1.77, mean = 0, sd = 1, col = "lightblue") # 在同一张图上叠加绘制z=-2.25左侧的面积,用白色覆盖 xpnorm(-2.25, mean = 0, sd = 1, col = "white", add = TRUE) # 添加两条竖线标记区间的左右边界 abline(v = c(-2.25, 1.77), lwd = 2, lty = 2, col = "darkred")
This works because add=TRUE tells R to draw the second plot on top of the first. The white fill erases the area left of -2.25, leaving only the blue area between -2.25 and 1.77.
方法2:用ggplot2自定义绘制(更灵活可控)
If you want more customization (like adding text labels for the area, or tweaking colors/themes), ggplot2 is a better bet. Here's a complete script:
library(ggplot2) # 生成标准正态分布的x值数据(范围覆盖常见z-scores) x_values <- seq(-4, 4, by = 0.01) normal_data <- data.frame(x = x_values, density = dnorm(x_values)) # 计算区间对应的面积值 interval_area <- pnorm(1.77) - pnorm(-2.25) # 绘制最终图形 ggplot(normal_data, aes(x = x, y = density)) + # 绘制正态分布曲线 geom_line(color = "darkblue", linewidth = 1) + # 填充区间内的面积 geom_area(data = subset(normal_data, x >= -2.25 & x <= 1.77), fill = "lightblue", alpha = 0.7) + # 添加边界竖线 geom_vline(xintercept = c(-2.25, 1.77), color = "darkred", linetype = "dashed", linewidth = 1) + # 添加面积数值标注 annotate("text", x = (-2.25 + 1.77)/2, y = 0.1, label = paste("Area =", round(interval_area, 3)), size = 5, color = "darkblue") + # 设置坐标轴和标题 labs(x = "Z-score", y = "Density", title = "Standard Normal Distribution: Area between Z=-2.25 and Z=1.77") + theme_minimal()
This gives you a clean, labeled plot where you can adjust every element (colors, line styles, text size) to your liking.
Quick side note: The exact area for this interval is ~0.955, which you can confirm with pnorm(1.77) - pnorm(-2.25).
内容的提问来源于stack exchange,提问作者CuriousJ

