48238

# midpoints returned by barplot function do not actually line up with midpoints of bars

I've been noticing that if I save a barplot object:

y <- seq(10,50,10) mp <- barplot(y)

and overlay a line

par(new=T) plot(mp, y, type="o")

then the points on the new plot do not line up with the middle of the bars in the bar plot.

However, if I don't use par(new=T) and instead do this:

mp <- barplot(y) lines(mp, y) points(mp,y)

then the points line up with the middle of the bars.

I want to plot the new line plot on a second axis, so I'd need to do something like par(new=T). Does anyone know how to have the midpoints line up properly?

Thanks

After brief investigation, I realized that the problem is that the x-axis of the two plots don't match up. See the code & plot below to see the problem.

y <- seq(10, 50, 10) mp <- barplot(y) axis(1) #barplot will use left and bottom axes par(new = T) plot(mp, y * 4, type = "o", axes = F) axis(4) axis(3) # this plot will use top and right axes

<img src="https://i.stack.imgur.com/tgsHF.png" alt="enter image description here">

So to fix this problem, you need to specify common xlim parameter for both plots.

mp <- barplot(y, xlim = c(0, length(y) + 1)) par(new = T) plot(mp,y*4,type='o', axes = F,ylab="", xlim=c(0,length(y)+1) ) + axis(4) + mtext("y*4",4)

<img src="https://i.stack.imgur.com/IIW9T.png" alt="enter image description here">