Reshaping time series data from wide to tall format (for plotting) [duplicate]

you can also use melt() from the ‘reshape’ library (I think it’s easier to use than reshape() itself) – that’ll save you the extra step of having to add the time column back in…

> library(reshape)
> m <- melt(dat,id="t",variable_name="symbol")
> names(m) <- sub("value","price",names(m))
> head(m)
           t symbol       price
1 2009-01-01      X -1.14945096
2 2009-01-02      X -0.07619870
3 2009-01-03      X  0.01547395
4 2009-01-04      X -0.31493143
5 2009-01-05      X  1.26985167
6 2009-01-06      X  1.31492397
> class(m$t)
[1] "Date"
> library(lattice)                                                              
> xyplot( price ~ t | symbol, data=m ,type ="l", layout = c(1,3) )

For this particular task, however, I would consider using the ‘zoo’ library, which would not require you to reshape the data frame:

> library(zoo)                                                                  
> zobj <- zoo(dat[,-1],dat[,1])                                                 
> plot(zobj,col=rainbow(ncol(zobj))) 

R developers/contributors (Gabor and Hadley in this case) have blessed us with many great choices. (and can’t forget Deepayan for the lattice package)

Leave a Comment