I have been trying to overlay base R xyplots overtop barplots with the same ylim values. Even using this dummy code:
data(mtcars)
barplot(mtcars$mpg,
ylim=c(0,40))
par(new=TRUE,xaxt="s",yaxt="s",bty="n");plot(20,20,ylim=c(0,40),pch=c(16))
The end result has the y-axis askew, where the midpoint lines up at 20, but all the other values of the axis are further off as they are larger or smaller than 20.
Can anyone explain why this happens and how I can avoid it in the future?
What you are looking for is the yxas
argument for the par
function.
From the documentation for xaxs
(which is the same as yaxs
for the x axis):
The style of axis interval calculation to be used for the x-axis. Possible values are "r", "i", "e", "s", "d". The styles are generally controlled by the range of data or xlim, if given.
Style "r" (regular) first extends the data range by 4 percent at each end and then finds an axis with pretty labels that fits within the extended range.
Style "i" (internal) just finds an axis with pretty labels that fits within the original data range.
Style "s" (standard) finds an axis with pretty labels within which the original data range fits.
Style "e" (extended) is like style "s", except that it is also ensures that there is room for plotting symbols within the bounding box.
Since we want to fit the axis, I gonna use the internal style:
data(mtcars)
barplot(mtcars$mpg,
ylim=c(0,40))
par(new=TRUE,yaxs="i", xaxt="s",yaxt="s",bty="n");plot(20,20,ylim=c(0,40),pch=c(16))
Output: