[R] Month tick marks on a plot()

Gavin Simpson gavin.simpson at ucl.ac.uk
Tue Jan 20 10:04:31 CET 2009


On Mon, 2009-01-19 at 23:39 +0000, glenn wrote:
> Hi All,
> 
> I have a small dataframe [dates, values) I am plotting with
> plot(df,type=l)
> 
> And the date date covers a year. The graph only have marks at 2008 and
> 2009.
> 
> How do I get the months labeled at the bottom please
> 
> Thanks as always
> 
> Glenn

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

> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: This is a digitally signed message part
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20090120/8dcc5b7b/attachment-0002.bin>


More information about the R-help mailing list