[R] xlims of barplot

Marc Schwartz MSchwartz at medanalytics.com
Thu Nov 13 14:49:07 CET 2003


On Wed, 2003-11-12 at 23:54, Paul Sorenson wrote:
> I would like to create a family of barplots with the same xlimits.  Is
> there a way to "read" the xlimits from the first graph so I can apply it to
> the subsequent ones?
> 
> I have tried just taking the min and max of the x data and the plot doesn't
> show.
> 
> cheers

A point of clarification:

When you say x axis limits, are you referring to the bar heights in a
horizontal barplot or are you referring to the range of the x axis with
vertical bars?  A critical difference.

In the former situation, you can explicitly set the x axis limits using
the 'xlim' argument to include the range of values in your various sets
of data. Thus, you can use:

# Get the maximum x value in the datasets
# Presumes that 'MyData' contains all values
max.x <- max(MyData)

# Now use this format for EACH barplot
barplot(...., horiz = TRUE, xlim = c(0, max.x))

That will result in the x axis being the same in each plot.  You might
want to use something like 'xlim = c(0, max.x * 1.25)', which will give
you some additional space above the bars (ie. for a legend, etc.).

Note that if you use the range of x values (instead of 0 and max) and
set xlim to that min/max pair, you will get a "funny" result. For
example:

barplot(1:5, horiz = TRUE, xlim = c(1, 5))

Since par("xpd") is set to TRUE by default in barplot(), the bases of
the bars will actually appear beyond the left side of the plot region.
You can eliminate that effect by using:

barplot(1:5, horiz = TRUE, xlim = c(1, 5), xpd = FALSE)

However, you will not see a bar for your minimum value.

If you are talking about a vertical barplot, then the x axis range will
be the same for each barplot under the following conditions, without
having to set it:

1. You have the same number of bars in each plot
2. You do not change the values of 'space', 'width' or 'beside' across
the plots.

Also, keep in mind that the bars are NOT centered over integer values on
the respective axis. You can get the bar center positions by using:

mp <- barplot(...)

where 'mp' will contain the bar midpoints, which is useful for
subsequent annotation, etc.

See ?barplot for more help and examples.

HTH,

Marc Schwartz




More information about the R-help mailing list