0

I've been trying to display data with two different y axis range values. This response was very helpful in doing this with barplot:

# data 1
yy <- c(30,45,60,100,110,90,80,50,20,10,10,15)
name1 <- month.abb
xx <- barplot(yy, ylab = "", names.arg = name1,col="steelblue", ylim = c(0,120))

# data 2
par(new = T)
yy2 <- c(20,21,21,22,23,23.5,22,20,19,19,18,19)
plot(xx + 0.5, yy2, "l", ylim = c(18,24), lwd = 2,col="red", lty=1, 
     axes=F, xlim=c(min(xx), max(xx)+1))
points(xx + 0.5, yy2, pch = 18, cex = 1,col="red")
axis(4)
box()

# example grid
abline(h = 18)
### abline 18 through 23
abline(h = 24)

resulting in this output

enter image description here

I wonder how can I align the grids between y axis. I guess stretching the secundary axis to the top and bottom of the box could do it but I can't figure it out how to do that stretching. Any advice?


EDIT. Looking for a nice way of putting a legend I found this response, which I think is very straightfoward.

noriega
  • 447
  • 1
  • 9
  • 23

1 Answers1

1

By default, plot adds an extra 4% all sides of the plot range. barplot does not do this. That is why your your two axes do not line up. You can turn off the extra added space by using the argument yaxs="i". Also, instead of using abline many times, I added the horizontal lines using grid. Putting this together, I get:

xx <- barplot(yy, ylab = "", names.arg = name1,col="steelblue", ylim = c(0,120))

# data 2
par(new = T)
yy2 <- c(20,21,21,22,23,23.5,22,20,19,19,18,19)
plot(xx + 0.5, yy2, "l", ylim = c(18,24), lwd = 2,col="red", lty=1, 
     axes=F, xlim=c(min(xx), max(xx)+1), yaxs="i")
points(xx + 0.5, yy2, pch = 18, cex = 1,col="red")
axis(4)
box()

grid(nx=1, ny=6, lty=1, col="black")

enter image description here

G5W
  • 36,531
  • 10
  • 47
  • 80