如何在 R 中点数很少的图上拟合平滑曲线

How to fit a smooth curve on a plot with very few points in R

我只有 4 个数据点:

points = c(60, 46, 46, 60)

那"want"来描述一条抛物线。但是,显然,我找不到使它顺利进行的方法;取而代之的是,我使用下面这些行的代码得到了下面红色的四四方方的图:

plot(points, ylim=c(40,60), pch = 20, col = 2, cex = 2)
fit = loess(points ~ c(1:4), bw=nrd0, na.rm=T)
lines(predict(fit), lwd=2, col= 2)

不知道有什么方法可以把边角弄光滑,这样看起来更像蓝线...

如您收到的消息所述,loess对这么少的点数不满意。但是你可以使用 spline:

得到一个漂亮的曲线
points = c(60, 46, 46, 60)
plot(points, ylim=c(40,60), pch = 20, col = 2, cex = 2)
lines(spline(1:4, points, n=100))

既然你想拟合一个二次方程,你就可以得到你想要的,如下所示。 假设二次函数是

f(x) = a*x^2 + b*x + c

那么我们就知道

a+b+c = 60
4a+2b+c = 46
9a+3b+c = 46

通过将 f(1),f(2),f(3) 等同于 points[1:3]。 由于对称性,我们可以忽略 points] 的第四个元素。 a,b,c是一组线性方程A %*% x = points的解。 所以构造矩阵A如下

A <- matrix(c(1,1,1,4,2,1,9,3,1),nrow=3,byrow=TRUE)

然后求解线性方程组:

pcoef <- solve(A,points[1:3])

现在得到你想要的图表

f <- function(x,pcoef)  pcoef[1]*x^2 + pcoef[2]*x + pcoef[3]
g <- function(x) f(x,pcoef)

plot(points, ylim=c(40,60), pch = 20, col = 2, cex = 2)
curve(g,from=1,to=4,add=TRUE, col="blue")