R中的3D样条曲线

时间:2016-10-29 07:57:53

标签: r plot 3d curve spline

说我有一个如下所示的数据集:

structure(list(z = c(8.98702764, 5.57518482, 6.98490607, 5.49062004, 
6.29710557, 2.94919278, 6.92608989, 12.7289712, 14.40415287, 
10.17410763, 11.668976, 10.591285, 11.99862788), y = c(97.6744227499797, 
137.901039454029, 121.13581870045, 104.862400564151, 100.555349411331, 
76.1737610946716, 73.0655202440326, 56.9068174248469, 54.9673280956043, 
50.3012220744035, 44.659247762082, 56.0656699448102, 52.8735636084187
), x = c(5.9213978165422, 5.95607210189104, 5.9234210229403, 
5.99177184112492, 6.01421304577101, 6.11577782296786, 6.12640154858096, 
6.29193626680413, 6.34553237084864, 6.37503341918741, 6.47851248698575, 
6.46627091526568, 6.44897610832035)), .Names = c("z", "y", "x"
), class = "data.frame", row.names = c(NA, 13L))

          z         y        x
1   8.987028  97.67442 5.921398
2   5.575185 137.90104 5.956072
3   6.984906 121.13582 5.923421
4   5.490620 104.86240 5.991772
5   6.297106 100.55535 6.014213
6   2.949193  76.17376 6.115778
7   6.926090  73.06552 6.126402
8  12.728971  56.90682 6.291936
9  14.404153  54.96733 6.345532
10 10.174108  50.30122 6.375033
11 11.668976  44.65925 6.478512
12 10.591285  56.06567 6.466271
13 11.998628  52.87356 6.448976

现在我想用R绘制一条平滑的三维曲线。在二维中(使用我的x和y变量),我会这样做:

plot.new() #otherwise xpsline() won't run
path<-as.data.frame(xspline(df[,c(2,3)], shape=-0.5, lwd=2, draw=F))

library(ggplot2)
p<-ggplot(data=path, aes(x,y))
p + geom_path()

enter image description here

不幸的是,xspline无法计算三维的样条曲线。有什么想法吗?

1 个答案:

答案 0 :(得分:5)

Duncan Murdoch关于R-help https://stat.ethz.ch/pipermail/r-help/2008-November/179848.html的建议建议在每个维度上独立平滑:

> t=1:13
> tt = seq(1,13,len=100)
> sdata = data.frame(
    x=splinefun(t, data$x)(tt),
    y=splinefun(t, data$y)(tt),
    z=splinefun(t, data$z)(tt))

使用rgl包来显示数据点:

> plot3d(data$x,data$y,data$z,size=40)
> lines3d(sdata$x,sdata$y,sdata$z)

为插值中的更多点增加tt的长度。