Antoni Parellada
Antoni Parellada

Reputation: 4791

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

I have just 4 data points:

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...

enter image description here

Upvotes: 1

Views: 5230

Answers (2)

Bhas
Bhas

Reputation: 1834

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]. We can ignore the fourth element of points] because of symmetry. The a,b,c are the solution of a set of linear equations A %*% x = points. So construct matrix A as follows

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")

enter image description here

Upvotes: 2

Vincent Bonhomme
Vincent Bonhomme

Reputation: 7433

As stated in the message you got, loess is not happy with so little points. But you can get a nice curve using 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))

enter image description here

Upvotes: 6

Related Questions