Javier Castillo Arnemann Javier Castillo Arnemann - 3 months ago 27
R Question

xlim and x-axis not the same in barplot

I am overlaying two bar plots with base graphics (as they have different scales and so far it's been a nightmare to do it on ggplot) of the following data:

> str(pidf)
'data.frame': 1300 obs. of 7 variables:
$ spec1 : num 0.00192 0.00213 0.00151 0.00234 0.00133 ...
$ spec2 : num 0.00241 0.00278 0.00189 0.00264 0.00155 ...
$ spec3 : num 0.00231 0.00262 0.00187 0.00274 0.00165 ...
$ spec4 : num 0.00209 0.0026 0.00166 0.00225 0.00165 ...
$ spec5 : num 0.0025 0.00285 0.00188 0.00285 0.00181 ...
$ numbers: int 1 2 3 4 5 6 7 8 9 10 ...
$ ratios : num 0.59 0.642 0.544 0.625 0.567 ...


This is my code for the plots:

par(mar = c(5,5,2,5))
barplot(pidf$ratios, col = "skyblue", ylim = c(0, 1),
ylab = "Sequenced Base Ratios", border = NA, main = "Chlorocebus tantalus")
axis(1, at = round(seq(0, 1300, 100)))
par(new = T)
barplot(pidf$spec5, col = "chartreuse3", border = NA, ylim = c(0, 0.003),
axes = F, xlab = NA, ylab = NA)
axis(side = 4)
mtext(side = 4, line = 3, expression(pi))
legend("topright", legend=c(expression(pi), "Ratios"), cex = 0.75,
pch=c(15, 15), col=c("chartreuse3", "skyblue"))


When I run this code the x-axis is shorter than the data

If I specify
xlim = c(1,1300)
in the first plot, then I get this


Does anybody know why this is happening, and how to fix it? I guess it might have to do with the par values, but I need those in order to have space for the axis I draw on the right. Thanks in advance!

Answer

I think the problem is that bars aren't automatically located at unit intervals. By default, barplot adds a gap of 0.2 units between bars (see ?barplot, search for "space"). For example, if we have 20 bars, the right edge of the x axis is at x=24:

z <- 1:20
barplot(z)
axis(side=1,at=c(0,24))

enter image description here

For your application it's probably easiest to fit this by specifying space=0:

barplot(z,space=0)
axis(side=1,at=c(0,20))

enter image description here

Comments