# 対応のある2変数の散布図とヒストグラムをxy座標で描画する関数 # 二つ目の関数は特定のものの散布図とヒストグラムを塗りつぶす layout.plot.hist <- function(x,y, ratio1=c(3,1), ratio2=c(1,3)){ # (左下,左上,右下,右上)の順に(1,2,3,0) 0は描画しない 分割を縦横それぞれ設定 layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), ratio1, ratio2, TRUE) # ヒストグラム情報を記録 x.counts <- hist(x, right=FALSE, plot=FALSE)$counts y.counts <- hist(y, right=FALSE, plot=FALSE)$counts # 左下画面 par(mar=c(3,3,1,1)) # 余白指定 plot(x, y, xlim=range(x), ylim=range(y)) # 散布図作成 # 左上画面 par(mar=c(0,3,1,1)) # 余白指定 barplot(x.counts, ylim=c(0,max(x.counts)), space=0, col=0) # 上ヒストグラム # 右下画面 par(mar=c(3,0,1,1)) # 余白指定 barplot(y.counts, xlim=c(0,max(y.counts)), space=0, horiz=TRUE, col=0) # 右ヒストグラム # layout.plot.hist(ind$sheath, ind$leaf, c(3,2), c(2,3)) } layout.plot.hist2 <- function(x,y, x2,y2, ratio1=c(3,1), ratio2=c(1,3)){ # (左下,左上,右下,右上)の順に(1,2,3,0) 0は描画しない 分割を縦横それぞれ設定 layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), ratio1, ratio2, TRUE) # ヒストグラム情報を記録 x.counts <- hist(x, right=FALSE, plot=FALSE)$counts y.counts <- hist(y, right=FALSE, plot=FALSE)$counts x.breaks <- hist(x, right=FALSE, plot=FALSE)$breaks y.breaks <- hist(y, right=FALSE, plot=FALSE)$breaks x2.counts <- hist(x2, right=FALSE, breaks=x.breaks, plot=FALSE)$counts y2.counts <- hist(y2, right=FALSE, breaks=y.breaks, plot=FALSE)$counts # 左下画面 par(mar=c(3,3,1,1)) # 余白指定 plot(x, y, xlim=range(x), ylim=range(y)) # 散布図作成 points(x2, y2, pch=16) # 塗りつぶし # 左上画面 par(mar=c(0,3,1,1)) # 余白指定 barplot(x.counts, ylim=c(0,max(x.counts)), space=0, col=0) # 上ヒストグラム barplot(x2.counts, ylim=c(0,max(x.counts)), space=0, col=1, add=T) # 右下画面 par(mar=c(3,0,1,1)) # 余白指定 barplot(y.counts, xlim=c(0,max(y.counts)), space=0, horiz=TRUE, col=0) # 右ヒストグラム barplot(y2.counts, xlim=c(0,max(y.counts)), space=0, horiz=TRUE, col=1, add=T) } # 使用方法 x <- runif(100) # 一様分布の乱数 y <- rnorm(100) # 正規分布の乱数 x2 <- x[1:30] # 一様分布の乱数 y2 <- y[1:30] # 正規分布の乱数 layout.plot.hist(x,y) # 作図 layout.plot.hist(x,y,c(1,1),c(1,1)) # 作図 layout.plot.hist2(x,y,x2,y2) # 作図 layout.plot.hist2(x,y,x2,y2,c(1,1),c(1,1)) # 作図