Multiple time series plots using ggplot2 with each

2019-09-06 02:21发布

问题:

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 ...

回答1:

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()



标签: r ggplot2