Question

Suppose i have 3 time series data "a","b","c", each of them has 2 variables to be record in 7 days.

Here goes the sample code:

require(data.table)  
#Create data
DT<-data.table(type=c(rep("a",7),rep("b",7),rep("c",7)), time=1:7,V1=rnorm(7*3,10,5),V2=rnorm(7*3,100,20),key="type")
# plot.zoo
require(zoo)
plot(zoo(DT["a"])[,3:4])

enter image description here

I am able to plot one type a time (as above), but i want to plot all "a" "b" "c"... into that panel, where different colors represents different type of time series.

So what i am looking for is a plot which has TWO panels (for "V1" and "V2"), and within each panel, there are several lines ("a","b","c"...) with different colors

Was it helpful?

Solution

Try this for zoo classic graphics, zoo lattice graphics and zoo ggplot2 graphics:

library(zoo)
z <- read.zoo(DT, split = 1, index = 2, FUN = identity)
Names <- read.table(text = names(z), sep = ".", col.names = c("screen", "col"))

plot(z, screen = Names$screen, col = Names$col) # also see note 3 below

library(lattice)
xyplot(z, screen = Names$screen, col = Names$col) # also see note 3 below


library(ggplot2) # also see note 4 below
m <- fortify(z, melt = TRUE)
m2 <- transform(m, screen = sub("\\..*", "", Series), col = sub(".*\\.", "", Series))
qplot(Index, Value, data = m2, col = col, geom = "line") + facet_wrap(~ screen)

Notes

1) If we just wanted separate panels it would just be plot(z), xyplot(z) and autoplot(z).

2) names(z) and Names are:

> names(z)
[1] "V1.a" "V2.a" "V1.b" "V2.b" "V1.c" "V2.c"
> Names
  screen col
1     V1   a
2     V2   a
3     V1   b
4     V2   b
5     V1   c
6     V2   c

3) We could have just hard coded it as this (in which case we would not need Names):

plot(z, screen = 1:2, col = c(1, 1, 2, 2, 3, 3))

xyplot(z, screen = 1:2, col = c(1, 1, 2, 2, 3, 3))

4) Here is a ggplot2 alternative not involving z. It converts DT to long form with data.table package and then performs the qplot:

long <- DT[, list(Series = names(.SD), Value = unlist(.SD)), by = list(type, time)]
qplot(time, Value, data = long, col = type, geom = "line") + facet_wrap(~ Series)

OTHER TIPS

Using lattice package for example , you can do this :

library(lattice)
xyplot(V1+V2~time,groups=type,data=DT,type='l')

enter image description here

You can also do it using ggplot2:

library(reshape2)
dt.m <- melt(DT,measure.vars=c('V1','V2'))

ggplot(dt.m) +
 geom_line(aes(x=time,y=value,group=type,color=type)) +
  facet_grid(~variable)

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top