[R] Ticks on barplots

Mike Prager mike.prager at noaa.gov
Thu Mar 22 18:43:41 CET 2007


Marc Schwartz <marc_schwartz at comcast.net> wrote:

> On Tue, 2007-03-20 at 18:04 -0400, Michael H. Prager wrote:
> > Dear Gurus,
> > 
> > Using R 2.4.1 on Windows XP
> > 
> > I am generating stacked barplots of age-composition of fish populations 
> > (Y) over time (X).  As there are many years, not every bars is labeled.  
> > When looking at the plot, it becomes difficult to associate labels with 
> > their bars.
> > 
> > We have improved this a bit by using axis() to add a tickmark below each 
> > bar.  Can anyone suggest a way to draw ticks ONLY at bars where a tick 
> > label is drawn?  Or to make such ticks longer than those where there is 
> > no label?
> > 
> > This is going into a function, so I'm hoping for a method that doesn't 
> > require looking at the plot first.
> > 
> >  [...]
> > 
> > Mike Prager
> > NOAA, Beaufort, NC
> 
> Mike,
> 
> How about something like this:
> 
>   mp <- barplot(1:50, axisnames = FALSE)
> 
>   # Create short tick marks at each bar
>   axis(1, at = mp, labels = rep("", 50), tcl = -0.25)
> 
>   # Create longer tick marks every 5 years with labels
>   axis(1, at = mp[seq(1, 50, 5)], 
>        labels = 1900 + seq(0, 45, 5), tcl = -0.75, las = 2, 
>        cex.axis = 0.75)
> 
> 
> Just pick which labels you want to be shown (eg. every 5 years) and
> synchronize the values of those with the 'at' argument in axis().


Based on your suggestion, I hacked together something more
general that works nicely for up to 200 bars, which exceeds the
range of data we expect.  A sample program looks like this:

# Make a bar chart with major and minor ticks
# Example R code
# M. H. Prager     22 Mar 2007 
nbars <- 200
# Make phony data and labels:
dataset <- abs(rnorm(nbars))
datalabels <- seq(from = 1949, along.with = dataset)
# Make barplot without x-axis:
mp <- barplot(t(dataset), xlab = "Year", ylab = "Numbers",
    axisnames = FALSE, space = 0)
# Get major and minor multiples for choosing labels:
ntick <- length(mp)
{   if (ntick < 16) mult = c(2, 2)
    else if(ntick < 41) mult = c(5, 5)
    else if (ntick < 101) mult = c(10, 5)
    else mult = c(20, 5)
}
label.index <- which(datalabels %% mult[1] == 0)
minor.index = which(datalabels %% mult[2] == 0)
# Draw all ticks:
axis(side = 1, at = mp, labels = FALSE, tcl = -0.2)
# Draw minor ticks:
axis(side = 1, at = mp[minor.index], labels = FALSE, tcl = -0.5)
# Draw major ticks & labels:
axis(side = 1, at = mp[label.index], labels =
datalabels[label.index], tcl = -0.7)


Mike

-- 
Mike Prager, NOAA, Beaufort, NC
* Opinions expressed are personal and not represented otherwise.
* Any use of tradenames does not constitute a NOAA endorsement.



More information about the R-help mailing list