如何在 r 中绘制置信区间
置信区间是可能包含具有一定置信水平的总体参数的值范围。
本教程介绍如何在 R 中绘制数据集的置信区间。
示例:在 R 中绘制置信区间
假设我们在 R 中有以下数据集,包含 100 行和 2 列:
#make this example reproducible set.seed(0) #create dataset x <- rnorm(100) y <- x*2 + rnorm(100) df <- data.frame(x = x, y = y) #view first six rows of dataset head(df) xy 1 1.2629543 3.3077678 2 -0.3262334 -1.4292433 3 1.3297993 2.0436086 4 1.2724293 2.5914389 5 0.4146414 -0.3011029 6 -1.5399500 -2.5031813
要创建 x 和 y 之间的关系图,我们可以首先拟合线性回归模型:
model <- lm(y ~ x, data = df)
接下来,我们可以使用abline()函数和lines() 函数创建估计的线性回归线图,以创建实际的置信带:
#get predicted y values using regression equation newx <- seq(min(df$x), max(df$x), length.out=100) preds <- predict(model, newdata = data.frame(x=newx), interval = 'confidence') #create plot of x vs. y, but don't display individual points (type='n') plot(y ~ x, data = df, type = 'n') #add fitted regression line abline(model) #add dashed lines for confidence bands lines(newx, preds[,3], lty = 'dashed', col = 'blue') lines(newx, preds[,2], lty = 'dashed', col = 'blue')
黑线显示拟合的线性回归线,而两条蓝色虚线显示置信区间。
或者,您还可以使用以下代码填充置信区间线和估计线性回归线之间的区域:
#create plot of x vs. y plot(y ~ x, data = df, type = 'n') #fill in area between regression line and confidence interval polygon(c(rev(newx), newx), c(rev(preds[,3]), preds[,2]), col = 'grey', border = NA) #add fitted regression line abline(model) #add dashed lines for confidence bands lines(newx, preds[,3], lty = 'dashed', col = 'blue') lines(newx, preds[,2], lty = 'dashed', col = 'blue')
这是从开始到结束的完整代码:
#make this example reproducible set.seed(0) #create dataset x <- rnorm(100) y <- x*2 + rnorm(100) df <- data.frame(x = x, y = y) #fit linear regression model model <- lm(y ~ x, data = df) #get predicted y values using regression equation newx <- seq(min(df$x), max(df$x), length.out=100) preds <- predict(model, newdata = data.frame(x=newx), interval = 'confidence') #create plot of x vs. y plot(y ~ x, data = df, type = 'n') #fill in area between regression line and confidence interval polygon(c(rev(newx), newx), c(rev(preds[,3]), preds[,2]), col = 'grey', border = NA) #add fitted regression line abline(model) #add dashed lines for confidence bands lines(newx, preds[,3], lty = 'dashed', col = 'blue') lines(newx, preds[,2], lty = 'dashed', col = 'blue')