2016-12-23 15 views
2

同じx値を重ねて2つのプロットを表示したい。しかし、プロットは整列しません。棒グラフでプロットをRに合わせる

どうすれば並べ替えることができますか?


コード:

dat <- data.frame(d = LETTERS[1:5], c = c(39, 371, 389, 378, 790), r = c(39, 
    332, 18, -11, 412)) 

par(mfrow=c(2,1)) 

plot(dat$c, type = "s", ylim = c(0, max(dat$c)), xlab = "", ylab = "", axes = FALSE, col = "#4572a7", lwd = 2) 
axis(1, at = c(1:length(dat$c)), labels = dat$d, lty = 0) 
axis(2, lty = 0, las = 1) 

barplot(dat$r, names.arg = dat$d, col = "#008000", border = NA, axes = FALSE) 
axis(2, lty = 0, las = 1) 
abline(h = 0, col = "#bbbbbb") 

enter image description here

答えて

1

私たちは、各バーの中心のx座標を取得し、最初のプロットのx値としてこれらの座標を使用する必要があります。また、各プロットに同じxlim値を設定する必要があります。

# Get x coordinates of center of each bar 
pr = barplot(dat$r, names.arg = dat$d, col = "#008000", border = NA, axes = FALSE, 
      plot=FALSE) 

par(mfrow=c(2,1)) 

# Apply the x coordinates we just calculated to both graphs and give both 
# graphs the same xlim values 
plot(pr, dat$c, type = "s", ylim = c(0, max(dat$c)), xlab = "", ylab = "", axes = FALSE, 
    col = "#4572a7", lwd = 2, xlim=range(pr) + c(-0.5,0.5)) 
axis(1, at = pr, labels = dat$d, lty = 0) 
axis(2, lty = 0, las = 1) 

barplot(dat$r, names.arg = dat$d, col = "#008000", border = NA, axes = FALSE, 
     xlim=range(pr) + c(-0.5,0.5)) 
axis(2, lty = 0, las = 1) 

enter image description here

関連する問題