LoginSignup
3
2

More than 3 years have passed since last update.

Rでスプライン曲線を描く

Posted at

概要

smooth.splineを使って点と点を滑らかに通るcubic smoothing spline curve(3次平滑化スプライン曲線)を描く。

使用例

今回は滑らかに結びたいデータセットxyを、適当な乱数を使って用意。

x <- rep(1:10)
y <- rnorm(10, mean=0.5, sd=0.2)
xy <- data.frame(x,y)

こんな感じのデータ

##     x         y
## 1   1 0.5731112
## 2   2 1.0058572
## 3   3 0.6335509
## 4   4 0.2445897
## 5   5 0.3784457
## 6   6 0.5662213
## 7   7 0.6725708
## 8   8 0.4708219
## 9   9 0.5967647
## 10 10 0.6542743

次に各種パラメータの設定。
new_xのlengthは、predict関数により予想される点の数である。
今回は、3種類のsparパラメータを使って平滑化スプライン曲線を描画した。

plot(xy[,1],xy[,2],xlim=c(1,10),ylim=c(0,1),
     xlab="x",ylab="y",cex=1)#xyをplotしておく

new_x <- seq(1,10,length=100)#予測される点の数
spar_i <- c(0,0.4,1)#sparパラメータの変更
col_i <- c("red","green","blue")#描画パラメータ

for(i in 1:3){
  sp <- smooth.spline(xy[,1],xy[,2],spar=spar_i[i])
  pred <- predict(sp,new_x)
  par(new=T)
  lines(lwd=1, pred, col=col_i[i])
}

こんな感じで点と点を滑らかに結んだ曲線が描かけた。必ずしも点を通るわけではないので注意。
smooth_spline.jpg

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2