我还很陌生,ggplot2
并希望生成一个具有多个散点图的图,并分别给出其回归估计值。但是,我使用的非标准回归方法(例如分位数回归和总回归)不在method
可用的参数列表之列geom_smooth()
。我有一个拟合模型和相应数据的列表。下面是一个工作示例。
require(data.table); require(ggplot2)
N <- 1000 # Generate some data
DT <- NULL
models <- list() # list of of fitted models. For simplicity i am using lm in this example
for(i in 1:8){
x <- rnorm(N)
y <- i*x + rnorm(N)
z <- rep(i,N)
DT <- rbind(DT,data.table(cbind(x=x,y=y,z=z)))
models[[i]] <- lm(y~x,DT)
}
# Traditional way to plot the data with regression estimates is to use geom_smooth
my.plot <- ggplot(DT, aes(x=x, y=y)) + geom_point() +
facet_wrap(~ z, nrow=2, ncol=4) +
geom_smooth(method = "lm", se=FALSE, color="red", formula = y ~ x)
my.plot
我需要一种在不拟合回归模型的情况下绘制红色回归估计值的方法geom_smooth
。是否有解决方法可以使我的单独清单与Models
兼容facet_wrap
?
由于尚不清楚如何将美观度映射到模型中使用的变量,因此需要自己计算线的值,然后将其添加为标准geom_line
层而不是使用geom_smooth
。例如
lines <- purrr::map_dfr(models, function(m) {
xrng <- range(m$model$x)
data.frame(x=xrng, y=predict(m, data.frame(x=xrng)))
}, .id="z")
ggplot(DT, aes(x=x, y=y)) + geom_point() +
facet_wrap(~ z, nrow=2, ncol=4) +
geom_line(color="red", data=lines)
请注意,此处的斜率看起来有些“偏离”,但这与您实际建模的模型匹配(您DT
每次都使用了整个模型)。如果要在每次迭代中分别估算斜率,则循环看起来应该更像
for(i in 1:8){
x <- rnorm(N)
y <- i*x + rnorm(N)
z <- rep(i,N)
chunk <- data.table(x=x,y=y,z=z)
models[[i]] <- lm(y~x,chunk)
DT <- rbind(DT, chunk)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句