将B样条拟合到控制路径

时间:2015-11-06 19:42:19

标签: r curve-fitting

我意识到在R中使用B样条有很多问题和答案,但我还没有找到这个(看似简单的)问题的答案。

给定一组描述控制路径的点,如何将B样条曲线拟合到该曲线并沿曲线绘制给定数量的点(比如100)。问题在于,路径在x和y都不是单调的。

示例控制路径:

path <- data.frame(
    x = c(3, 3.5, 4.6875, 9.625, 5.5625, 19.62109375, 33.6796875, 40.546875, 36.59375, 34.5, 33.5, 33),
    y = c(0, 1, 4, 5, 6, 8, 7, 6, 5, 2, 1, 0)
)

我主要看了splines包,但是大多数例子都是关于为数据拟合平滑曲线。对于上下文,我正在考虑在R中实现hierarchical edge bundling

1 个答案:

答案 0 :(得分:2)

一般的想法是独立地预测x和y,假设它们实际上是独立的:

library(splines)

path <- data.frame(
    x = c(3, 3.5, 4.6875, 9.625, 5.5625, 19.62109375, 33.6796875, 40.546875, 36.59375, 34.5, 33.5, 33),
    y = c(0, 1, 4, 5, 6, 8, 7, 6, 5, 2, 1, 0)
)
# add the time variable
path$time  <- seq(nrow(path))

# fit the models
df  <-  5
lm_x <- lm(x~bs(time,df),path)
lm_y <- lm(y~bs(time,df),path)

# predict the positions and plot them
pred_df  <-  data.frame(x=0,y=0,time=seq(0,nrow(path),length.out=100) )
plot(predict(lm_x,newdata = pred_df),
     predict(lm_y,newdata = pred_df),
     type='l')

您需要注意定义时间变量,因为路径不依赖于时间选择(即使它们是连续的),因为样条曲线对预测变量空间中的点间距不是不变的。例如:

plotpath  <-  function(...){
    # add the time variable with random spacing
    path$time  <- sort(runif(nrow(path)))

    # fit the models
    df  <-  5
    lm_x <- lm(x~bs(time,df),path)
    lm_y <- lm(y~bs(time,df),path)

    # predict the positions and plot them
    pred_df  <-  data.frame(x=0,y=0,time=seq(min(path$time),max(path$time),length.out=100) )
    plot(predict(lm_x,newdata = pred_df),
         predict(lm_y,newdata = pred_df),
         type='l',...)
}

par(ask=TRUE); # wait until you click on the figure or hit enter to show the next figure
for(i in 1:5)
    plotpath(col='red')