[R] Plotting monthly timeseries with an x-axis in "time format"
Gabor Grothendieck
ggrothendieck at gmail.com
Mon Dec 3 20:40:16 CET 2007
This can be done with plot.zoo and a panel function:
tab <- ts(cbind(A = c(79.47, 89.13, 84.86, 75.68, 72.82, 78.87, 93.46,
78.18, 82.46, 77.25, 80.95, 84.39, 81.7, 74.76, 65.29, 60.3,
66.59, 73.19, 92.39, 65.76, 77.45, 74.22, 101.36, 100.01), B = c(77.95,
76.73, 51.2, 51.86, 51.29, 49.45, 53.88, 47.96, 55.07, 45.34,
37.07, 37.53, 47.79, 37.5, 30.35, 37.78, 34.13, 39.14, 39.89,
35.46, 36.54, 38.39, 47.33, 45.34)), start = c(2006, 1), freq = 12)
library(zoo)
pnl.xaxis <- function(...) {
lines(...)
panel.number <- parent.frame()$panel.number
nser <- parent.frame()$nser
# if bottom panel
if (!length(panel.number) || panel.number == nser) {
tt <- list(...)[[1]]
ym <- as.yearmon(tt)
mon <- as.numeric(format(ym, "%m"))
yy <- format(ym, "%y")
mm <- substring(month.abb[mon], 1, 1)
axis(1, tt[mon == 1], yy[mon == 1], cex.axis = 0.7)
axis(1, tt[mon > 1], mm[mon > 1], cex.axis = 0.5, tcl = -0.3)
}
}
plot(as.zoo(tab), panel = pnl.xaxis, xaxt = "n")
On Dec 3, 2007 12:11 PM, vittorio <vdemart1 at tin.it> wrote:
> I have the following timeseries "tab"
> =====================================
> > str(tab)
> mts [1:23, 1:2] 79.5 89.1 84.9 75.7 72.8 ...
> - attr(*, "dimnames")=List of 2
> ..$ : NULL
> ..$ : chr [1:2] "Ipex...I" "Omel...E"
> - attr(*, "tsp")= num [1:3] 2006 2008 12
> - attr(*, "class")= chr [1:2] "mts" "ts"
>
> > tab
> Ipex...I Omel...E
> Jan 2006 79.47 77.95
> Feb 2006 89.13 76.73
> Mar 2006 84.86 51.20
> Apr 2006 75.68 51.86
> May 2006 72.82 51.29
> Jun 2006 78.87 49.45
> Jul 2006 93.46 53.88
> Aug 2006 78.18 47.96
> Sep 2006 82.46 55.07
> Oct 2006 77.25 45.34
> Nov 2006 80.95 37.07
> Dec 2006 84.39 37.53
> Jan 2007 81.70 47.79
> Feb 2007 74.76 37.50
> Mar 2007 65.29 30.35
> Apr 2007 60.30 37.78
> May 2007 66.59 34.13
> Jun 2007 73.19 39.14
> Jul 2007 92.39 39.89
> Aug 2007 65.76 35.46
> Sep 2007 77.45 36.54
> Oct 2007 74.22 38.39
> Nov 2007 101.36 47.33
> Dec 2007 100.01 45.34
> ===============================
>
> Plotting tab with a simple "plot(tab,plot.type="single")" I'm obtaining a
> graph with the x axis in an orrible decimal format so that,e.g., Jan 2006 is
> 2006.0 and Nov 2006 is 2006.8(33)!
>
> Instead I would like to see the x-axis in a more human-readable format, for
> instance, 12 tics for each year and a label at the beginning of each quarter
> of the year: 2006.1, 2006.4,2006.7.
> - OR -
> more elegantly, I would like to have the 12 tics with the month shortened
> labels: Jan, Feb, etc. and below, say June, one label for the year.
>
> Please help.
>
> Ciao
> Vittorio
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list