【问题标题】:Fit a B spline to a control path将 B 样条拟合到控制路径
【发布时间】:2015-11-06 19:42:19
【问题描述】:

我意识到在 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

【问题讨论】:

    标签: r curve-fitting


    【解决方案1】:

    总体思路是独立预测 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')
    

    【讨论】:

    猜你喜欢
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多