日々のつれづれ

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

棒グラフのいろいろ・その2

実験結果を棒グラフにするとき、エラーバーを描くことが多かった。
エクセルだとオプションで追加できるから、Rで描けないとまずい。

  • barplot関数で描くとき

これはarrows関数と組み合わせる。

> x <- matrix(sample(1:5,25,replace=TRUE),ncol=5
+ ,dimnames=list(letters[1:5],LETTERS[1:5]))
> y <- sample(5:10,25,replace=TRUE)/20
> 
> jpeg("barplot3.jpg")
> # barplotはx軸の座標を返すことができる
> (z <- barplot(x,main="write error bar",beside=TRUE,ylim=c(0,max(x+y)),col=cm.colors(5)))
     [,1] [,2] [,3] [,4] [,5]
[1,]  1.5  7.5 13.5 19.5 25.5
[2,]  2.5  8.5 14.5 20.5 26.5
[3,]  3.5  9.5 15.5 21.5 27.5
[4,]  4.5 10.5 16.5 22.5 28.5
[5,]  5.5 11.5 17.5 23.5 29.5
> arrows(x0=z,y0=x+y,x1=z,y1=x-y,length=.05,angle=90,code=3)
> dev.off()

で、こんな感じ。

ここでは"z <- barplot(...)"がミソで、エラーバーのx座標を指定できる。
これを利用すると、こんなグラフもかける。

> jpeg("barplot4.jpg")
> z <- barplot(x,main="write star",beside=TRUE,ylim=c(0,max(x+y)+1)
+ ,col=c(rep(cm.colors(5),2),rep(terrain.colors(5),3)))
> abline(v=z[5,2]+diff(z)[1],lwd=1.5)
> arrows(x0=z,y0=x+y,x1=z,y1=x-y,length=.05,angle=90,code=3)
> lines(rep(z[c(1,3),1],each=2),c(max((x+y)[c(1,3),1])+c(-2.2,.5,.5,.2)))
> text(x=z[2,1],y=max((x+y)[c(1,3),1])+.5,labels="***",pos=3)
> mtext(text="A & B",side=1,line=2,outer=FALSE,at=z[5,1]+diff(z)[1])
> mtext(text="C & D & E",side=1,line=2,outer=FALSE,at=z[3,4])
> dev.off()

で、こんな感じ。

でも、必死になって自作していると必ずパッケージに出くわす。
gplotsパッケージはとても使いやすい

  • barplots関数

エラーバーや背景線とか、引数がたくさんあって楽しい。

> library("gplots")
> jpeg("barplot5.jpg")
> barplot2(x,main="barplot2 of gplots package",beside=TRUE,ylim=c(0,max(x+y)+1),col=cm.colors(5)
+ ,ci.l=x+y,ci.u=x-y,plot.ci=TRUE,plot.grid=TRUE)
> dev.off()

で、こんな感じ。