rggplot2spline

Smooth spline through all data points + predictng values


I'm trying to create a smooth spline (possibly natural spline) to get a smoother curve between 7 data points. I feel the solution is simple, but still can't get my head around it.

Here's my data:`

structure(list(time = c(7269, 21935, 43200, 86400, 172800, 259200, 
518400), speed = c(5.804787454, 4.558924, 3.88888889, 3.21296296, 
2.44675926, 1.9437728, 1.88)), row.names = c(NA, -7L), class = c("tbl_df", 
"tbl", "data.frame"))

And here's how it looks with straight lines between the points. How do I fit the data to a smoother curve that still goes through all data points?

enter image description here

It seems, actually, that I can create a smoother curve with xspline. But then it is not as easy as using predict to get the y values of a given x. But maybe that's still the way to go?


Solution

  • library(splines)
    s <- interpSpline(speed ~ time, dd)
    p <- predict(s, x = seq(min(dd$time), max(dd$time), length.out = 101))
    plot(speed ~ time, dd)
    with(p, lines(x, y))
    

    enter image description here

    Note that this is an interpolation spline but not a monotonic spline ... a little bit of googling suggests that demography::cm.spline() might get you a monotonic interpolation spline