1. ホーム
  2. r

[解決済み] 2種類のY軸でプロットするにはどうしたらいいですか?

2022-07-19 02:18:29

質問

私は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)

どのように解決するのですか?

更新 : の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 から ジャンク・チャート ) と同様に Stephen Fewによるこの記事 (この記事では、「二重尺度軸を持つグラフは決して有用ではない、ときっぱりと結論づけることはできませんが、他のよりよい解決策に照らして、それを必要とする状況が思い当たらないということだけです。) のポイント4も参照してください。 この漫画 ...

もしあなたが決心しているなら、基本的なレシピは、最初のプロットを作成し、セット par(new=TRUE) を設定して R がグラフィックデバイスをクリアしないようにし、 2 番目のプロットを axes=FALSE を設定します (そして xlabylab を空白にする -。 ann=FALSE も使えるはずです)、そして axis(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"))

<イグ

同様のレシピは、棒グラフ、ヒストグラムなど、異なるタイプのプロットを重ね合わせるために使用できます。