日々のつれづれ

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

凡例(legend関数)について

legend関数は引数が多く、par関数でグラフィックパラメータを調整すれば、細かいアレンジができるので便利。
barplot関数のように、引数で凡例を持つ関数もある。

  • 四隅にlegendを描きたいときは、"topleft","topright","bottomleft","bottomright"を指定する。
> dat <- cbind(A=sample(10,3),B=sample(10,3),C=sample(10,3))
> 
> jpeg("legend.jpg")
> matplot(t(dat),col=1:3,lwd=1:3,pch=20,type="b",xlim=c(0,3)+.5,xaxt="n")
> axis(side=1,at=1:3,labels=colnames(dat))
> legend("topleft",legend=colnames(dat),pch=20,col=1:3,lwd=1:3,lty=1:3,title="topleft") # 左上
> legend("topright",legend=colnames(dat),pch=20,col=1:3,lwd=1:3,lty=1:3,title="topright") # 右上
> legend("bottomleft",legend=colnames(dat),pch=20,col=1:3,lwd=1:3,lty=1:3,title="bottomleft") # 左下
> legend("bottomright",legend=colnames(dat),pch=20,col=1:3,lwd=1:3,lty=1:3,title="bottomright") # 右下
> dev.off()

で、こんな感じ

  • 細かく指定したいとき
> jpeg("legend2.jpg")
> matplot(t(dat),col=1:3,lwd=1:3,pch=20,type="b",xlim=c(-1,5),ylim=c(0,9),xaxt="n")
> axis(side=1,at=1:3,labels=colnames(dat))
> # x,yでlegendの起点を指定、xjust=0,yjust=1なら左上
> legend(x=-.9,y=9,legend=colnames(dat),pch=20,col=1:3,lwd=1:3,lty=1:3
+ ,xjust=0,yjust=1,title="xjust=0,yjust=1")
> # x,yでlegendの起点を指定、xjust=0,yjust=0なら左下
> legend(x=-.9,y=0,legend=colnames(dat),pch=20,col=1:3,lwd=1:3,lty=1:3
+ ,xjust=0,yjust=0,title="xjust=0,yjust=0")
> # x,yでlegendの起点を指定、xjust=1,yjust=1なら右下
> legend(x=5,y=0,legend=colnames(dat),pch=20,col=1:3,lwd=1:3,lty=1:3
+ ,xjust=1,yjust=0,title="xjust=1,yjust=0")
> # x,yでlegendの起点を指定、xjust=1,yjust=1なら右下
> legend(x=5,y=6,legend=colnames(dat),pch=20,col=1:3,lwd=1:3,lty=1:3
+ ,xjust=1,yjust=1,title="xjust=1,yjust=1")
> # insetは内側に寄せる("topleft"から5%内側)
> legend("topright",legend=colnames(dat),pch=20,col=1:3,lwd=1:3,lty=1:3
+ ,inset=.05,,title="topright,inset=.05")
> dev.off()

で、こんな感じ

  • legendを横に並べる
> jpeg("legend3.jpg")
> matplot(t(dat),col=1:3,lwd=1:3,pch=20,type="b",xlim=c(0,3)+.5,ylim=c(0,10),xaxt="n")
> axis(side=1,at=1:3,labels=colnames(dat))
> # horizで横組み
> legend("topleft",legend=colnames(dat),horiz=TRUE,pch=20,col=1:3,lwd=1:3,lty=1:3,title="horiz=TRUE")
> # ncolは横列数を指定
> legend("topright",legend=colnames(dat),ncol=2,pch=20,col=1:3,lwd=1:3,lty=1:3,title="ncol=2")
> dev.off()

で、こんな感じ

  • legendを外に出したいとき

barplotはlegend.textを引数にもつけど、枠線の色は黒になってしまう…

> jpeg("legend4.jpg")
> par(mai=c(.8,.8,.8,1.2)) # 右端のスペースを開ける
> par(xpd=FALSE) # グラフエリア外にプロットしない
> barplot(t(dat),beside=TRUE,col=cm.colors(3),border=1:3
+ ,legend.text=colnames(dat)) # barの色だけ引き継ぐ、legendはinsetが入る
> box()
> 
> # そこで、グラフエリア外にちゃんとした凡例を描いてみる
> par(xpd=TRUE) # グラフの外を指定する
> legend(x=par()$usr[2],y=par()$usr[4],legend=colnames(dat),pch=22,lty=0,xjust=-.1
+ ,pt.bg=cm.colors(3),col=1:3,pt.cex=2,x.intersp=2,y.intersp=1.5,title="xpd=TRUE")
> # legendの左上が起点となって、
> # x=par()$usr[1]は左端に揃う
> # x=par()$usr[2]は右端に揃う
> # y=par()$usr[3]は下に揃う
> # y=par()$usr[4]は上に揃う
> dev.off()

で、こんな感じ

legend関数は引数が多すぎて、理解に苦しむところもありますね。
まあ、凝りすぎても仕方ないですが…

わたやんさんどうですかね?