Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolating a path/curve within R

Within R, I want to interpolate an arbitrary path with constant distance between interpolated points.

The test-data looks like that:

require("rgdal", quietly = TRUE)
require("ggplot2", quietly = TRUE)
r <- readOGR(".", "line", verbose = FALSE)
coords <- as.data.frame(r@lines[[1]]@Lines[[1]]@coords)
names(coords) <- c("x", "y")
print(coords)

x         y
-0.44409  0.551159
-1.06217  0.563326
-1.09867  0.310255
-1.09623 -0.273754
-0.67283 -0.392990
-0.03772 -0.273754
 0.63633 -0.015817
 0.86506  0.473291
 1.31037  0.998899
 1.43934  0.933198
 1.46854  0.461124
 1.39311  0.006083
 1.40284 -0.278621
 1.54397 -0.271321

p.orig <- ggplot(coords, aes(x = x, y = y)) + geom_path(colour = "red") + 
    geom_point(colour = "yellow")
print(p.orig)

http://i.imgur.com/0tusA.png

I tried different methods, none of them were really satisfying:

  • aspline (akima-package)
  • approx
  • bezierCurve
  • with the tourr-package I couldn't get started

aspline

aspline from the akima-package does some weird stuff when dealing with arbitrary paths:

plotInt <- function(coords) print(p.orig + geom_path(aes(x = x, y = y), 
    data = coords) + geom_point(aes(x = x, y = y), data = coords))
N <- 50        # 50 points to interpolate

require("akima", quietly = TRUE)
xy.int.ak <- as.data.frame(with(coords, aspline(x = x, y = y, n = N)))
plotInt(xy.int.ak)

http://i.imgur.com/GVoES.png

approx

xy.int.ax <- as.data.frame(with(coords, list(x = approx(x, n = N)$y, 
    y = approx(y, n = N)$y)))
plotInt(xy.int.ax)

http://i.imgur.com/pqvTy.png

At first sight, approx looks pretty fine; however, testing it with real data gives me problems with the distances between the interpolated points. Also a smooth, cubic interpolation would be a nice thing.

bezier

Another approach is to use bezier-curves; I used the following implementation

source("bez.R")
xy.int.bz <- as.data.frame(with(coords, bezierCurve(x, y, N)))
plotInt(xy.int.bz)

http://i.imgur.com/aCFPG.png

like image 740
michelk Avatar asked Jul 06 '12 06:07

michelk


2 Answers

How about regular splines using the same method you used for approx? Will that work on the larger data?

Spline graph

xy.int.sp <- as.data.frame(with(coords, list(x = spline(x)$y, 
                                             y = spline(y)$y)))
like image 172
sebastian-c Avatar answered Sep 22 '22 15:09

sebastian-c


Consider using xspline or grid.xspline (the first is for base graphics, the second for grid):

plot(x,y, type='b', col='red')
xspline(x,y, shape=1)

enter image description here

You can adjust the shape parameter to change the curve, this example just plots the x spline, but you can also have the function return a set of xy coordinates that you would plot yourself.

like image 28
Greg Snow Avatar answered Sep 19 '22 15:09

Greg Snow