Lili Matic
Lili Matic

Reputation: 59

Time Series Plot Matrix

I have a question concerting R: I was trying to plot a set of daily time series commodity data in R with the package ggplot2 and ggfortify into a matrix. I am trying to have standardized values on each y axis and the dates 1/1/2007, 1/1/2008... on the x axis. The visual concept should look like this:

enter image description here

Does anyone know how that works ?

Upvotes: 3

Views: 1671

Answers (1)

Achim Zeileis
Achim Zeileis

Reputation: 17193

The zoo package provides support for time series with flexible time indexes, e.g., including Date. The package also brings a fortify() method that can be leveraged for ggplot2 graphics. A convenience method for autoplot() is also provided, see ?autoplot.zoo for a selection of worked examples with different layouts.

For an example with 18 time series with Date index in a 3 x 6 layout, I use a subset of the data set FXRatesCHF from package fxregime. This provides exchange rates for different currencies with respect to the Swiss Franc (CHF).

library("zoo")
data("FXRatesCHF", package = "fxregime")
FX <- window(FXRatesCHF[, c(1:4, 6:19)], start = as.Date("2000-01-01"))

Then ggplot() can be applied to the output of the fortify() method:

library("ggplot2")
ggplot(aes(x = Index, y = Value), data = fortify(FX, melt = TRUE)) +
  geom_line(color = "darkred") +
  xlab("Time") + ylab("FX") +
  theme_bw() +
  facet_wrap(~ Series, scales = "free_y", ncol = 6)

FX ggplot2

The same kind of layout can also be easily created with base graphics. Only the panel titles are on the y-axis rather than in a gray-shaded main title:

plot(FX, col = "darkred", xlab = "Time", nc = 6,
  panel = function(...) { grid(col = "lightgray"); lines(...) })

FX base graphics

Finally, a lattice version can be created by

library("lattice")
trellis.par.set(theme = standard.theme(color = FALSE))
xyplot(FX, col = "darkred", xlab = "Time", layout = c(6, 3),
  panel = function(...) { panel.grid(col = "lightgray"); panel.lines(...) })

FX lattice

Upvotes: 4

Related Questions