MarioT MarioT - 7 months ago 32
R Question

Y-Axis positions of barplot and base plot do not match

I was trying to plot a climate diagram and ran into the following problem:
After using barplot(...) for precipitation I superimposed another plot for the temperature. It is necessary for climate diagrams that the two y-axes (mm, °C) align at zero and that the precipitation/temperature ratio is 2:1 (e.g. 20mm precipitation corresponds to 10°C).

The problem: barplot(...) draws the axis to the plot's box while plot(...) leaves some space between the box and the axis margins.

Here is a simplified example. From the grid lines you see that the 0-values do not align:

plot(0:10, xlim=c(-2,14), axes=FALSE)
axis(4,at=c(0:10), labels=c(0:10))

enter image description here

How can I get the right position and scaling of the two axes?


Don't use par(new = TRUE):

lines(0:10, type = "p")
axis(4,at = c(0:10), labels = seq(0,20,2))

The function lines() is the right one here. The argument type = p is needed to plot points. You need to adjust the y-values for the temperature, but now the second y-axis is in the right way, I think.