0

I am looking for some help with multiple time series plot as per the following description.

I have a data frame with the following structure. Column isin is repeating and it has 5 unique values. For each isin, there are multiple rows of data consisting of t_week, MS and t_MS. Each isin has unequal number of rows. In another words, the data frame has 2 time series (t_week, MS) (t_week, t_MS) for each isin with unequal number of data points.

I would like to plot all the 5 isin time series (t_week, MS) on a single plot using ggplot2. I can plot multiple time series of equal length easily, but looking for help here doing it right "The R" way. Please help.

regards

K

str(df)
'data.frame':   95 obs. of  4 variables:
 $ isin  : chr  "IN0019960056" "IN0019960056" "IN0019960056" "IN0019960056" ...
 $ t_week: Date, format: "2006-01-09" "2006-01-16" ...
 $ MS    : num  0 0 0.01 0.86 0.54 0.23 1.55 0.07 0.29 0.79 ...
 $ t_MS  : num  0.14 0.14 0.14 0.75 0.35 0.31 0.63 0.28 0.54 0.52 ...
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
kishore
  • 541
  • 1
  • 6
  • 18

1 Answers1

3

The canocial ggplot2 way is the following:

ggplot(df, aes(x = t_week, y = MS, color = isin)) + geom_line()

this wil construct a plot of t_week vs MS, with a differently colored line for each unique element in isin. It is no problem that the timeseries do not consist of the same number of rows, they don't even have to cover the same time range. An example:

df_part1 = data.frame(t_week = seq(1,5,length=100), MS = runif(100), isin = "A")
df_part2 = data.frame(t_week = seq(2,6,length=500), MS = runif(500) + 1, isin = "B")
df = rbind(df_part1, df_part2)

library(ggplot2)
ggplot(df, aes(x = t_week, y = MS, color = isin)) + geom_line()

enter image description here

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • This is awesome @Paul. Thanks a bunch. I was trying all sort of combinations using ddply and melt leading to non-sensible plots. Didn't occur to me that ISINs can be treated as categorical variables and ggplot will do the trick finally. Once again thanks for excellent solution. – kishore May 11 '13 at 13:04
  • If this solves your problem, you can mark it as such by clicking the green tick mark to the left, right next to my answer. – Paul Hiemstra May 11 '13 at 13:44