2015-09-25 57 views
0

我第一次在R中使用stat_smooth(),我想知道是否有一种方法可以获得,对于每个xdata(y)和预测间隔之间的距离,你可以看到这里的图片:预测间隔和数据之间的距离(stat_smooth)

enter image description here

谢谢您的宝贵帮助!

+1

你可以分享你的数据和你用来使用'dput(data)'产生图的代码吗? –

+0

如何处理区间内的数据点?对于这些情况:'距离== 0'? –

+2

请阅读关于[如何提出一个好问题](http://stackoverflow.com/help/how-to-ask)以及如何生成[最小可重现示例]的信息(http://stackoverflow.com/问题/ 5963269 /如何对做 - 一个伟大-R-重复性,例如/ 5963610#5963610)。这会让其他人更容易帮助你。 – Jaap

回答

0

正如上面评论中指出的那样,澄清你的目标会有所帮助。

如果你想复制,ggplot2做什么,并找到间隔以外的点距离,我有一些代码给你。

首先,我创建了一些样本数据,并绘制它:

library(ggplot2) 
# sample data 
set.seed(1234) 
x <- c(1:100) 
y <- c(1:100) + rnorm(100, sd = 5) 
df <- data.frame(x, y) 

ggplot(df, aes(x, y)) + geom_point(alpha = .4) + stat_smooth(span = .3) 

plot_output

然后我复制什么ggplot2呢:我建立一个黄土模型(ggplot2选择黄土如果n < 1000),我随后使用以相同的方式建立置信区间stat_smooth注意:模型的参数需要与您在stat_smooth中使用的参数相匹配。

# find model, matching the span parameter from the graph above 
model <- loess(y ~ x, data = df, span = 0.3) 

# find x sequence 
xseq <- sort(unique(df$x)) 

# function adapted from ggplot2::predictdf.loess: 
# https://github.com/hadley/ggplot2/blob/f3b519aa90907f13f5d649ff6a512fd539f18b2b/R/stat-smooth-methods.r#L45 
predict_loess <- function(model, xseq, level = 0.95) { 
    pred <- stats::predict(model, newdata = data.frame(x = xseq), se = TRUE) 

    y_pred = pred$fit 
    ci <- pred$se.fit * stats::qt(level/2 + .5, pred$df) 
    ymin = y_pred - ci 
    ymax = y_pred + ci 

    data.frame(x = xseq, y_pred, ymin, ymax, se = pred$se.fit) 
} 

# predict your data 
predicted_data <- predict_loess(model, xseq, level = 0.95) 

# merge predicted data with original y 
merged_data <- with(df, cbind(predicted_data, y)) 

head(merged_data) 
# x  y_pred  ymin  ymax  se   y 
# 1 1 -0.5929504 -5.8628535 4.676953 2.652067 -5.035329 
# 2 2 0.2828659 -4.1520646 4.717796 2.231869 3.387146 
# 3 3 1.1796057 -2.5623056 4.921517 1.883109 8.422206 
# 4 4 2.1074914 -1.0994171 5.314400 1.613870 -7.728489 
# 5 5 3.0696584 0.2371895 5.902127 1.425434 7.145623 
# 6 6 4.0568034 1.4454944 6.668113 1.314136 8.530279 

从复制的数据中,我们现在可以找到距离。对于区间内的情况,它返回0

distances <- with(merged_data, ifelse(y < ymin, ymin - y, 
             ifelse(y > ymax, y - ymax, 0))) 
head(distances) 
# [1] 0.000000 0.000000 3.500689 6.629071 1.243496 1.862167 

这不是一个非常优雅的解决方案,但它可以指出你在正确的方向。