2つの異なるY軸でプロットするにはどうすればいいですか? 質問する

2つの異なるY軸でプロットするにはどうすればいいですか? 質問する

R で 2 つの散布図を重ねて、各点セットに独自の (異なる) y 軸 (つまり、図の位置 2 と 4) を持たせ、点が同じ図に重ねて表示されるようにしたいと思います。

でこれを行うことは可能ですかplot?

編集問題を示すサンプルコード

# example code for SO question
y1 <- rnorm(10, 100, 20)
y2 <- rnorm(10, 1, 1)
x <- 1:10
# in this plot y2 is plotted on what is clearly an inappropriate scale
plot(y1 ~ x, ylim = c(-1, 150))
points(y2 ~ x, pch = 2)

ベストアンサー1

アップデート: R wikiに掲載されていた資料をコピーしましたhttp://rwiki.sciviews.org/doku.php?id=tips:graphics-base:2yaxes、リンクが壊れています:こちらからも入手可能ウェイバックマシン

同じプロット上の2つの異なるy軸

(一部の資料は元々 Daniel Rajdl によるものです 2006/03/31 15:26)

同じプロットに 2 つの異なるスケールを使用することが適切な状況はほとんどないことに注意してください。グラフの閲覧者を誤解させる可能性が非常に高くなります。この問題に関する次の 2 つの例とコメントを確認してください (例1例2からジャンクチャート)、 同様にこの記事はスティーブン・フューによるものです(結論としては、「私は、二重スケールの軸を持つグラフが決して役に立たないとは断言できません。ただ、他のより良い解決策を考慮すると、二重スケールの軸を持つグラフが役に立つ状況は思いつきません。」)また、この漫画...

決心したら、基本的なレシピは、最初のプロットを作成し、par(new=TRUE)R がグラフィック デバイスをクリアしないように を設定し、2 番目のプロットを で作成しaxes=FALSE(および を空白に設定しxlabても機能するはずです)、次に を使用して右側に新しい軸を追加し、を使用して右側に軸ラベルを追加することです。以下に、少し架空のデータを使用した例を示します。ylabann=FALSEaxis(side=4)mtext(...,side=4)

set.seed(101)
x <- 1:10
y <- rnorm(10)
## second data set on a very different scale
z <- runif(10, min=1000, max=10000) 
par(mar = c(5, 4, 4, 4) + 0.3)  # Leave space for z axis
plot(x, y) # first plot
par(new = TRUE)
plot(x, z, type = "l", axes = FALSE, bty = "n", xlab = "", ylab = "")
axis(side=4, at = pretty(range(z)))
mtext("z", side=4, line=3)

twoord.plot()パッケージでは、パッケージplotrixと同様に、このプロセスが自動化されます。doubleYScale()latticeExtra

別の例 (Robert W. Baer による R メーリング リストの投稿から引用):

## set up some fake test data
time <- seq(0,72,12)
betagal.abs <- c(0.05,0.18,0.25,0.31,0.32,0.34,0.35)
cell.density <- c(0,1000,2000,3000,4000,5000,6000)

## add extra space to right margin of plot within frame
par(mar=c(5, 4, 4, 6) + 0.1)

## Plot first set of data and draw its axis
plot(time, betagal.abs, pch=16, axes=FALSE, ylim=c(0,1), xlab="", ylab="", 
   type="b",col="black", main="Mike's test data")
axis(2, ylim=c(0,1),col="black",las=1)  ## las=1 makes horizontal labels
mtext("Beta Gal Absorbance",side=2,line=2.5)
box()

## Allow a second plot on the same graph
par(new=TRUE)

## Plot the second plot and put axis scale on right
plot(time, cell.density, pch=15,  xlab="", ylab="", ylim=c(0,7000), 
    axes=FALSE, type="b", col="red")
## a little farther out (line=4) to make room for labels
mtext("Cell Density",side=4,col="red",line=4) 
axis(4, ylim=c(0,7000), col="red",col.axis="red",las=1)

## Draw the time axis
axis(1,pretty(range(time),10))
mtext("Time (Hours)",side=1,col="black",line=2.5)  

## Add Legend
legend("topleft",legend=c("Beta Gal","Cell Density"),
  text.col=c("black","red"),pch=c(16,15),col=c("black","red"))

ここに画像の説明を入力してください

同様のレシピを使用して、棒グラフやヒストグラムなど、さまざまな種類のグラフを重ね合わせることもできます。

おすすめ記事