日々のつれづれ

不惑をむかえ戸惑いを隠せない男性の独り言

直線とか曲線とか・その3

もう少し、続き

  • curve関数

曲線を描く関数です。関数を直接、指定できます。
座標を返すので、値が欲しいときに重宝します。

> jpeg("curve.jpg")
> 
> par(mfrow=c(2,2))
> curve(x+1/x,main=expression(x+frac(1,x))) # defaultは0から1
> curve(sin,from=-pi,to=pi,main="sin") # 単項の場合は変数は不要
> dat <- curve(x^3-5*x^2+3*x+4,from=-1,to=4,n=20,main=expression(x^3-5*x^2+3*x+4))
> # f <- function(x)x^3-5*x^2+3*x+4 
> # dat <- curve(f,from=-1,to=4,n=20) # function関数で指定もできる
> str(dat) # curveの返り値はlist、引数nで刻み幅が決まる
List of 2
 $ x: num [1:20] -1 -0.7368 -0.4737 -0.2105 0.0526 ...
 $ y: num [1:20] -5 -1.33 1.35 3.14 4.14 ...
> plot(dat,type="l",main=expression(x^3-5*x^2+3*x+4)) # 同じグラフになる
> dev.off()


で、変化量に対する、別の変数の変量を見たいときは、

> y <- curve(sin,from=-pi,to=pi,n=50)
> dat <- t(sapply(y$"y",function(y)curve(cos(x)+sin(y),from=-pi,to=pi,n=20)$"y"))
> jpeg("curve2.jpg",width=720)
> layout(t(1:2))
> par(mai=c(0,0,0,0))
> persp(x=1:50,y=1:20,z=dat,phi=30,theta=-60,shade=TRUE
+ ,xlab="sin(y)",ylab="cos(x)+sin(y)")
> library(fields)
> par(mai=c(.8,.8,.2,.2))
> image.plot(dat,col=terrain.colors(40),xlab="sin(y)",ylab="cos(x)+sin(y)"
+ ,axes=FALSE,horizontal=TRUE)
> dev.off()


ちょっとだけ、嬉しい機能。

  • rect関数

矩形を描く関数。4点の座標を指定する必要がある。

> jpeg("rect.jpg")
> plot(NA,xlim=c(0,3),ylim=c(0,3),ann=FALSE)
> rect(xleft=.5,ybottom=0,xright=2.5,ytop=2.2,lwd=2) # 四隅の座標を指定する
> rect(xleft=1,ybottom=.2,xright=2,ytop=.4,border=2) # borderは枠の色
> rect(xleft=c(.7,1.8),ybottom=1,xright=c(1.2,2.3),ytop=1.8,col=1) # ベクトルも 可
> rect(xleft=c(.2,2.2),ybottom=2,xright=c(.8,2.8),ytop=2.8,col=1) # 上書きされる
> rect(xleft=c(.8,1.9,1.4),ybottom=c(rep(1.3,2),.8),xright=c(1.1,2.2,1.6)
+ ,ytop=c(rep(1.4,2),1),col=c(rep("white",2),"black")) # colはベクトルの順
> rect(xleft=c(.6,1.9),ybottom=.6,xright=c(1.1,2.4),ytop=.9,density=10,angle=45,col=6) # 斜線も可
> dev.off()

で、こんな感じ。

どちらも、ちょっとだけ嬉しい関数でした。