[R] Barplot and line x-axis positions

Jim Lemon jim at bitwrit.com.au
Wed Jan 19 11:00:47 CET 2011

On 01/19/2011 04:04 AM, Andy Aldersley wrote:
> Hello all,
> Hoping that there is a fairly simple solution to my query...
> I'm trying to overlay a line plot of some data onto a barplot of different data. The y-axes are different for each set of data but the x-axes are the same (1:12, corresponding with 12 months of observations). The problem I'm having is that the centre of the bars and the points on line don't match up, which is making the whole thing look untidy. I'm wondering if there is a way for me to specify the positions of the centre of each bar on the graph. The code I have is as follows:
> xvals<- barplot(wetMeans[,i], yaxt='n', axisnames=F, xlab='', ylab='', main=names[i], border=F, cex.main=0.7)par(new=T)plot(burnMeans[,i], yaxt='n', xlab='', ylab='', type='b', cex=1, pch=16, lty=44, col='black', lwd=1.5)
> As you can see I have suppressed the y-axis so this isn't a problem.I have also tried using the barp function in the plotrix package. This solved the problem of centring the bars on the graph, but when I overlay the line it seems to use different tick points on the x-axis. Again, I'm not sure why this is but if there is a quick fix that would be much appreciated.
> library(plotrix)xvals<- barp(wetMeans[,i], xlab='', ylab='', main=names[i], col='grey')par(new=T)plot(burnMeans[,i], yaxt='n', xlab='', ylab='', type='b', cex=1, pch=16, lty=44, col='black', lwd=1.5)
> I get the same result even if I suppress the x-axis in the plot command.

Hi Andy,
You seem to be heading in the right direction. barplot returns the 
centers of the bars, and if you use the "lines" function to draw your 
lines with these as the x values, you should get the lines in the 
correct place.

barp centers the bars on integer values by default, and returns both the 
x and y values in a list. Again, using "lines" should do what you want. 
If you are trying to use "plot" to get the lines, beware, you may not 
get the same plot extents unless you specify xlim= for both. If this 
doesn't help, try sending some real or fake data and a sample plot.


More information about the R-help mailing list