r - 从 LOESS 图导出结果
问题描述
我在该主题上找到了这篇文章,并且能够像帖子中所说的那样将其导出: 我可以从 R 中导出黄土回归的结果吗?
然而,正如该帖子中海报的最后一条评论所说,我没有得到我的 LOESS 线的结果。有没有人对如何让它正确导出有任何见解?
谢谢!
我的导出代码在这里:
#loess object
CL111_loess <- loess(dur_cleaned~TS_LightOn, data = CL111)
#get SE
CL111_predict <- predict(CL111_loess, se=T)
CL111_ouput <- data.frame("fitted" = CL111_predict$fit, "SE"=CL111_predict$se.fit)
write.csv(CL111_ouput, "CL111_output.csv")
原始图的数据在这里:
我的原始情节的代码在这里:
{r}
#individual plot
ggplot(data = CL111) + geom_smooth(mapping = aes(x = TS_LightOn, y = dur_cleaned), method = "lm", se = FALSE, colour = "Green") +
labs(x = "TS Light On (Seconsd)", y = "TS Response Time (Seconds)", title = "Layout 1, Condition AO, INS High") +
theme(plot.title = element_text(hjust = 0.5)) +
stat_smooth(mapping = aes(x = TS_LightOn, y = dur_cleaned), method = "loess", se = TRUE) + xlim(0, 400) + ylim (0, 1.0)
#find coefficients for best fit line
lm(CL111_LM$dur_cleaned ~ CL111_LM$TS_LightOn)
解决方案
您可以通过 获取此信息ggplot_build()
。
如果您的绘图保存为gg1
,运行ggplot_build(gg1)
;然后您必须检查data
对象(这是不同层的数据列表)并尝试找出您需要的层(在这种情况下,我查找了哪个数据层包含colour
与平滑线匹配的列...
bb <- ggplot_build(gg1)
## extract the right component, just the x/y coordinates
out <- bb$data[[2]][,c("x","y")]
## check
plot(y~x, data = out)
你现在可以用这个输出做任何你想做的事情(write.csv()
, save()
, saveRDS()
...)
我同意有些奇怪/我不了解ggplot2
设置黄土拟合的方式。您确实必须predict()
与权利有关newdata
(例如,具有单列TS_LightOn
范围从 0 到 400 的数据框) - 否则您会得到数据集中点的预测,这些点可能没有正确间隔/以正确的顺序 - 但是这并不能解决我的差异。