我有以下图片:
我想平滑红线和蓝线。但我不知道该怎么做。红色和蓝色线分别代表上部和上部。黑点的间隔减少了95%。 (请注意,我没有使用任何回归公式来获得95%的间隔) 我读到了关于黄土功能但是当我试图使用它时。我得到了同样的情节。 那么是否有任何特殊的内置R函数可以让我平滑这两行。
或者,有没有办法为这个问题获得“95%点间隔”?
代码如下:
residual.plot <- function(a,b)
{
log.y1 <- log(a) - b * log(energy)
fitted.y <- exp(log.y1)
diff <- count - fitted.y
#normal approximation
low.interval <- c()
high.interval <- c()
for(i in 1:350)
{
low <- diff[i] - sqrt( exp(log(a) - b * log(energy[i])) )*qnorm(0.975)
high <- diff[i] + sqrt( exp(log(a) - b * log(energy[i])) )*qnorm(0.975)
low.interval <- append(low.interval, low)
high.interval <- append(high.interval, high)
}
par(mfrow = c(1,1))
plot(energy, diff, ylim = c(-10,10), type = "p", pch = 7)
lines(energy, low.interval, type = "p", col = "red", pch = 1)
lines(energy, high.interval, type = "p", col = "blue", pch = 1)
}
答案 0 :(得分:5)
首先,再也不敢发布这样的代码了。你犯了两个致命罪:
这就是说,最简单的方法是使用lowess
,前提是数据中没有NA值。你的功能应该是这样的:
residual.plot <- function(a,b,count,energy)
{
log.y1 <- log(a) - b * log(energy)
fitted.y <- exp(log.y1)
diff <- count - fitted.y
#normal approximation
low <- diff - sqrt( exp(log(a) - b * log(energy)) )*qnorm(0.975)
high <- diff + sqrt( exp(log(a) - b * log(energy)) )*qnorm(0.975)
par(mfrow = c(1,1))
plot(energy, diff, ylim = c(-10,10), type = "p", pch = 7)
lines(lowess(energy, low), type = "p", col = "red", pch = 1)
lines(lowess(energy, high), type = "p", col = "blue", pch = 1)
}
PS:要使函数有用,您不应该依赖函数外部的变量,例如count
和energy
。将它们作为参数添加到函数中,以便稍后在使用其他数据集时可以使用该函数。