An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20130305/58bce50e/attachment.pl>
ggplot2: two time series with different dates in a single plot
2 messages · Matthijs Daelman, Gabor Grothendieck
On Tue, Mar 5, 2013 at 3:30 PM, Matthijs Daelman
<matthijs.daelman at gmail.com> wrote:
Hi Using the ggplot2 package, I would like to obtain a plot that contains two time series that have data points on different dates. For instance, one data frame looks like: date1, value1 2010-01-05, 2921.74 2010-01-08, 2703.89 2010-01-14, 3594.21 2010-01-20, 3659.22 The other data frame looks like date2, value2 2010-01-01, 285.85 2010-01-02, 229.20 2010-01-05, 333.91 2010-01-06, 338.27 2010-01-07, 272.85 2010-01-08, 249.04 2010-01-09, 240.07 2010-01-10, 255.06 2010-01-11, 275.42 2010-01-12, 252.39 I would like to plot these two time series in one and the same plot, with date on the X axis and value on the Y axis. And while you're at it: how would you proceed to get a secondary Y axis for the second dataframe?
Lines1 <- "date1, value1 2010-01-05, 2921.74 2010-01-08, 2703.89 2010-01-14, 3594.21 2010-01-20, 3659.22" Lines2 <- "date2, value2 2010-01-01, 285.85 2010-01-02, 229.20 2010-01-05, 333.91 2010-01-06, 338.27 2010-01-07, 272.85 2010-01-08, 249.04 2010-01-09, 240.07 2010-01-10, 255.06 2010-01-11, 275.42 2010-01-12, 252.39" library(zoo) library(ggplot2) # create two zoo time series objects z1 <- read.zoo(text = Lines1, header = TRUE, sep = ",") z2 <- read.zoo(text = Lines2, header = TRUE, sep = ",") # combine them into a single multivariate time series z <- na.approx(merge(z1, z2)) # single panel autoplot(z, facet = NULL) # or, multiple panels with different Y axes autoplot(z) + facet_free() Different left and right are generally frowned upon but if you want that anyways look at the examples in ?plot.zoo -- Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com