[英]How to fit a smooth curve on a plot with very few points in R
I have just 4 data points: 我只有4个数据点:
points = c(60, 46, 46, 60)
that "want" to describe a parabola. 那个“想”形容抛物线。 Evidently, though, I can't find a way to make it smooth;
显然,我找不到一种使它平滑的方法。 instead, I end up with the boxy plot in red below using code along these lines:
取而代之的是,我使用下面这些行代码,最终得到了下面红色方框图:
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)
I wonder if there is any way of making the corners smooth, so that it looks more like the blue line... 我想知道是否有任何方法可以使拐角平滑,使其看起来更像蓝线...
Since you want to fit a quadratic you can get what you want as follows. 由于您想拟合二次方,因此可以按以下方式获得所需的结果。 Assume the quadratic function is
假设二次函数为
f(x) = a*x^2 + b*x + c
then we know that 那么我们知道
a+b+c = 60
4a+2b+c = 46
9a+3b+c = 46
by equating f(1),f(2),f(3)
with points[1:3]
. 通过将
f(1),f(2),f(3)
等同于points[1:3]
。 We can ignore the fourth element of points]
because of symmetry. 由于对称性,我们可以忽略
points]
的第四个元素。 The a,b,c
are the solution of a set of linear equations A %*% x = points
. a,b,c
是一组线性方程A %*% x = points
。 So construct matrix A
as follows 因此,如下构建矩阵
A
A <- matrix(c(1,1,1,4,2,1,9,3,1),nrow=3,byrow=TRUE)
and then solve the linear equations: 然后求解线性方程:
pcoef <- solve(A,points[1:3])
Now to get the graph you want do 现在获取您想要的图形
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.