legend関数

MikuHatsune2012-08-07

legend関数の使い方でググったのでメモ。

par(mfrow=c(2, 2))
dat <- cbind(A=sample(10,3),B=sample(10,3),C=sample(10,3))

#1枚目
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") # 右下

#2枚目
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")

#3枚目
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")

#4枚目
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]は上に揃う