使用ggplot2和facet_wrap绘制估计值而无需重新拟合模型

JustGettin开始

我还很陌生,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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用facet_wrap和ggplot2在每个构面内绘制整个数据

使用facet_wrap在ggplot2中绘制时间序列数据

使用ggplot2和facet_wrap显示不同的轴标签

使用ggplot2结合facet_wrap和95%的密度图面积

在ggplot2中使用facet_wrap和scales =“ free”设置单个轴限制

ggplot2 facet_wrap在每个构面上绘制点,线段和文本

ggplot2中的facet_wrap()和facet_grid()有什么区别?

R:在 ggplot2 中重新标记 facet_wrap 标题

在ggplot2中使用facet_wrap时,通过两个轴上的相同值跟踪直线

ggplot无法使用facet_wrap和group asthetic绘制流畅的游戏

在ggplot2和facet_wrap中具有表达式的as_labeller

Facet_wrap和scale =“ free”意外地使ggplot2中的y轴居中于零

R // ggplot2:结合facet_wrap和for循环时的动态标题

在 ggplot2 中向 facet_wrap 添加下标和符号

GGplot2:从面板中移除部件 (facet_wrap)

从默认更改ggplot2 :: facet_wrap标题

控制facet_wrap ggplot2中的x标签

ggplot2 facet_wrap的文本标签

如何从ggplot2 facet_wrap删除构面?

ggplot2 facet_wrap与数学表达式

ggplot2 :: facet_wrap()的默认面板布局?

使用facet_wrap时ggplot重新排序更改

在ggplot2中使用labeller更改facet_wrap标签

ggplot2 facet_wrap:仅使用每个组中存在的x轴标签

使用 ggplot2 中的 facet_wrap 对线图倍数进行排序

R: ggplot2 使用 facet_wrap 设置中间的最后一个图

如何使用ggplot2的facet_wrap创建时间序列图

使用facet_wrap()时无法控制ggplot2中的legend.position

ggplot2 - 使用 facet_wrap 時如何有兩種配色方案?