将B样条曲线拟合到控制路径 [英] Fit a B spline to a control path

查看:184
本文介绍了将B样条曲线拟合到控制路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I realise lots of questions and answers exists on the use of B-splines in R, but I have yet to find an answer to this (seemingly simple) question.

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

Given a set of points that describe a control path, how do you fit a B-spline curve to that and extract a given number of points (say 100), along the curve for plotting. The catch is that the path is not monotonous in neither x, nor 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)
)

我主要看过样条线程序包,但同样,大多数示例都在考虑拟合平滑曲线数据。对于上下文,我正在考虑实现分层边缘捆绑在R.

I've mainly looked at the splines package but again, most examples has been regarding fitting a smooth curve to data. For context, I'm looking at implementing hierarchical edge bundling in R.

推荐答案

总体思路是假设x和y实际上是独立的,从而对其进行独立预测:

The general idea is to predict x and y independently, assuming they are in fact independend:

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

您确实需要谨慎定义时间变量,因为路径并非独立于时间选择(即使它们是顺序的),因为样条曲线在预测变量中的点间距也不是不变的空间。例如:

you do need to be careful about defining your time variable, since the path is not independent of choice of times (even when they're sequential) since splines are not invariant on the spacing of points in the predictor space. For example:

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

这篇关于将B样条曲线拟合到控制路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆