我有这样的数据帧:
> dat
x y yerr
1 -1 -1.132711 0.001744498
2 -2 -2.119657 0.003889120
3 -3 -3.147378 0.007521881
4 -4 -4.220129 0.012921450
5 -5 -4.586586 0.021335644
6 -6 -5.389198 0.032892630
7 -7 -6.002848 0.048230946
我可以用标准误差为平滑绘制它:
p <- ggplot(dat, aes(x=x, y=y)) + geom_point()
p <- p + geom_errorbar(data=dat, aes(x=x, ymin=y-yerr, ymax=y+yerr), width=0.09)
p + geom_smooth(method = "lm", formula = y ~ x)
但我需要的是使用yerr适合我的线性模型。 是否有可能与GGPLOT2?
嗯,我找到了一种方法来回答这个问题。
因为在任何科学实验,我们收集的数据,如果该实验是正确执行,所有的数据值必须有相关的错误。
在某些情况下,误差的方差可能是在所有点相等,但在很多,像本案中原来的问题指出,事实并非如此。 所以,以曲线拟合我们的数据时,我们必须使用不同的在不同的测量误差值的变化。
这样做是将重量归因于误差值,根据统计分析方法,其等于1 / SQRT(errorValue),因此,它变成:
p <- ggplot(dat, aes(x=x, y=y, weight = 1/sqrt(yerr))) +
geom_point() +
geom_errorbar(aes(ymin=y-yerr, ymax=y+yerr), width=0.09) +
geom_smooth(method = "lm", formula = y ~ x)
对于任何模型拟合,我将尽我所用的绘图范式的配件之外。 为此,将值传递给weights
是反比于观测的差异。 嵌合将随后经由加权最小二乘法来完成。
对于示例/情况ggplot的geom_smooth
为你做以下。 惠斯特它可能看起来更容易使用geom_Smooth
,拟合模型的好处直接最终超过这一点。 首先,你必须拟合模型,并能在合适的模型假设等进行诊断
适应加权最小二乘
mod <- lm(y ~ x, data = dat, weights = 1/sqrt(yerr))
然后predict()
从模型上的范围x
newx <- with(dat, data.frame(x = seq(min(x), max(x), length = 50)))
pred <- predict(mod, newx, interval = "confidence", level = 0.95)
在上面我们得到predict.lm
方法来生成使用适当的置信区间。
接下来,准备绘制数据
pdat <- with(data.frame(pred),
data.frame(x = newx, y = fit, ymax = upr, ymin = lwr))
其次,建立剧情
require(ggplot2)
p <- ggplot(dat, aes(x = x, y = y)) +
geom_point() +
geom_line(data = pdat, colour = "blue") +
geom_ribbon(mapping = aes(ymax = ymax, ymin = ymin), data = pdat,
alpha = 0.4, fill = "grey60")
p
你的问题是有点含糊。 这里有一对夫妇可以让你开始说的建议。
GGPLOT2只是使用lm
回归功能。 要获得这些值,只是做:
lm(y ~ x, data=dat)
这会给你截距和梯度。
您可以在关闭标准错误stat_smooth
使用se
参数:
.... + geom_smooth(method = "lm", formula = y ~ x, se = FALSE)
您可以通过点/误差带与添加功能区:
##This doesn't look good. .... + geom_ribbon(aes(x=x, ymax =y+yerr, ymin=y-yerr))
文章来源: Using smooth in ggplot2 to fit a linear model using the errors given in the data