Skip to content

Month tick marks on a plot()

4 messages · glenn, jim holtman, Gabor Grothendieck +1 more

#
?axis
On Mon, Jan 19, 2009 at 6:39 PM, glenn <g1enn.roberts at btinternet.com> wrote:

  
    
#
The zoo faq has an example:

library(zoo)
vignette("zoo-faq") # see question 8
On Mon, Jan 19, 2009 at 6:39 PM, glenn <g1enn.roberts at btinternet.com> wrote:
#
On Mon, 2009-01-19 at 23:39 +0000, glenn wrote:
Hi,

Here is an example using standard data types:

## some dummy data
x <- seq(as.Date("2008-01-01"), as.Date("2009-10-31"), by = "day")
set.seed(1234)
y <- cumsum(rnorm(length(x)))

## plot, but suppress axes
plot(y ~ x, type = "l", axes = FALSE)
## add in axis on side 2
axis(2)

## compute where we want the ticks for the months
ticks.at <- seq(min(x), max(x),
                by = "months")
## format the labels as abbreviated month names
ticks.lab <- format(ticks.at, format = "%b")
## indicator variable; is month January?
m1 <- ticks.lab == "Jan"
## plot small ticks and labels for months not Jan
Axis(x, at = ticks.at[!m1], side = 1, 
     labels = ticks.lab[!m1], las = 2, cex.axis = 0.7)
## plot the default tick locations for years
Axis(x, side = 1, las = 2)
## add the box
box()

You may have to process the last call to Axis to get the years if R
doesn't produce them for you, perhaps:

Axis(x, at = ticks.at[m1], las = 2, side = 1,
     labels = format(ticks.at[m1], format = "%Y"))

Notice the calls to Axis(). This will call the appropriate axis() method
for the class of object 'x' (in this case). This just means that you
don't need to remember to call axis.Date (and get capitalisation
correct). All the calls to Axis can be done with axis.Date explicitly
but you'll need to swap the first two arguments (me being lazy and not
naming 'x' argument)

HTH

G