我用 geom_line 和 geom_ribbon 创建了一个图(图 1),结果还不错,但为了美观,我希望线条和丝带更平滑。我知道我可以使用 geom_smooth 来绘制线条(图 2),但我不确定是否可以平滑功能区。我可以为功能区的顶线和底线创建一条 geom_smooth 线(图 3),但是无论如何要填充这两行之间的空间吗?
实现您想要的目标的一个原则方法是使用 mgcv 中的 gam() 函数将 GAM 模型拟合到您的数据,然后在预测变量的更精细的值网格上将该函数应用于该模型。网格可以覆盖由预测变量的观测值范围定义的跨度。下面的 R 代码通过一个具体示例说明了这一过程。
# load R packages
library(ggplot2)
library(mgcv)
# simulate some x and y data 
# x = predictor; y = response
x <- seq(-10, 10, by = 1) 
y <- 1 - 0.5*x - 2*x^2 + rnorm(length(x), mean = 0, sd = 20)
d <- data.frame(x,y)
# plot the simulated data 
ggplot(data = d, aes(x,y)) + 
geom_point(size=3)
# fit GAM model
m <- gam(y ~ s(x), data = d) 
# define finer grid of predictor values
xnew <- seq(-10, 10, by = 0.1) 
# apply predict() function to the fitted GAM model
# using the finer grid of x values
p <- predict(m, newdata = data.frame(x = xnew), se = TRUE) 
str(p) 
# plot the estimated mean values of y (fit) at given x values
# over the finer grid of x values;
# superimpose approximate 95% confidence band for the true 
# mean values of y at given x values in the finer grid
g <- data.frame(x = xnew, 
            fit = p$fit,
            lwr = p$fit - 1.96*p$se.fit, 
            upr = p$fit + 1.96*p$se.fit)
head(g) 
theme_set(theme_bw())
ggplot(data = g, aes(x, fit)) + 
geom_ribbon(aes(ymin = lwr, ymax = upr), fill = "lightblue") + 
geom_line() + 
geom_point(data = d, aes(x, y), shape = 1)
如果您要使用 lm() 函数将多项式回归模型拟合到数据,则同样的原则也适用。
| 归档时间: | 
 | 
| 查看次数: | 5511 次 | 
| 最近记录: |