[R] Space between bars in barplot

Marc Schwartz MSchwartz at MedAnalytics.com
Thu Jan 13 19:01:45 CET 2005


On Thu, 2005-01-13 at 16:43 +0000, michael watson (IAH-C) wrote:
> Hi
> 
> I am trying to understand the "space" argument to barplot() and I think
> it is not working as stated.  The docs say:
> 
>   space: the amount of space (as a fraction of the average bar width)
>           left before each bar.
> 
> Which means that I can pass a vector, the same length as the no. of
> bars, and the nth element of that vector will be the space left before
> the nth bar.  This is always true except for the FIRST bar.  Eg:
> 
> barplot(c(1,2,3,4),space=c(1,1,1,1))  # equally spaced bars as expected
> 
> barplot(c(1,2,3,4),space=c(1,20,1,1))  # massive gap before the 2nd bar
> 
> barplot(c(1,2,3,4),space=c(20,1,1,1))  # the same as the first plot
> 
> I'm guessing this is going to be something to do with par().... any idea
> how I can adjust the space between the x-axis and the first bar?


Upon a quick review, it looks like the calculation in question here is
at line 62 in barplot.R:

   w.l <- w.m - delta

In this case, 'w.m' contains the calculated bar midpoints, adjusted for
the 'space' and 'width' arguments (using your third example):

   # width is 1 by default

   delta <- width / 2                # equals 0.5 0.5 0.5 0.5
   w.r <- cumsum(space + width)      # equals 21 23 25 27
   w.m <- w.r - delta                # equals 20.5 22.5 24.5 26.5
   w.l <- w.m - delta                # equals 20 22 24 26

The 'xlim' for the plot is then set to:

  if (missing(xlim)) xlim <- c(min(w.l), max(w.r))

In the case of your third example, xlim is set to:

   20 27

and the bar midpoints are in wm, which means that bar 1 (mp = 20.5) runs
from 20 - 21. Since the left side of the x axis is set to 20, it does
not leave the defined space (20) to the left of the bar. Some space is
there as a result of the adjustment to the axis ranges by default (see
the help for par("xaxs").

If the calculation in line 62 were set to:

  w.l <- w.m - delta - space[1]

that would do the trick here, but I have not considered the impact of
that change elsewhere in the code, before considering recommending that
it get modified by R Core.

The alternative, would be to simply change the language in the help for
barplot() to explicitly indicate that the 'space' does not apply to the
first bar:

  space: the amount of space (as a fraction of the average bar width)
         left before each bar, with the exception of the first bar.
         Thus, space[1] has no effect if given as a vector.


As a temporary fix, you could explicitly specify the xlim argument:

  barplot(1:4, space=c(20, 1, 1, 1), xlim = c(0, 27))

Now, of course, I calculated the min,max values from the above code. You
could replicate the same calculations prior to calling barplot() and
then adjust xlim as you require to use with your actual data.

HTH,

Marc Schwartz




More information about the R-help mailing list