2

Consider the (simplistic) version of this zoo object:

d <-  c("2007-01-31", "2007-02-28", "2007-03-31", "2007-04-30", "2007-05-31", "2007-06-30", "2008-02-28", "2008-03-31", "2008-04-30", "2009-09-30", "2009-10-31", "2009-11-30", "2009-12-31", "2010-01-31")
vec <- runif(14, 0.5, 0.7)
vec.zoo = zoo(vec, order.by = as.Date(d, format = "%Y-%m-%d"))
plot(vec.zoo, ylim = c(0,1))

As you can see, some dates are missing (look at the index d). However, when I plot the object, I get the following:

enter image description here

I realize that this is feasible with ggplot, however the outcome is multiple plots instead of one (See thread: link)

I would like to be able to draw the zoo object in a one plot, but by leaving a blank space in the plot when no data is available for a specific date. How can I do that?

Thanks!

Community
  • 1
  • 1
Mayou
  • 8,498
  • 16
  • 59
  • 98

2 Answers2

2

Assuming the frequency of your data is 'monthly':

library(zoo)
library(lubridate) # for easy extraction of different components of date object

# convert 'd' to monthly data
d2 <- as.yearmon(d)


# create zoo object
z1 <- zoo(vec, order.by = d2)


# create a continuous series of monthly data, ranging from min(d) to max(d)
d3 <- as.Date(d)
tt <- as.yearmon(min(year(d)) + seq(month(min(d)) - 1, (year(max(d)) - year(min(d))) * 12)/12)


# expand z1 to a continuous series
z2 <- merge(z1, zoo(, tt))


plot(z2)

enter image description here

Henrik
  • 65,555
  • 14
  • 143
  • 159
  • The frequency of my data is monthly indeed, and this answer does the job. Thank you! – Mayou Nov 15 '13 at 15:05
  • 1
    Glad to hear that you found my answer helpful! – Henrik Nov 15 '13 at 15:06
  • However, I have one small little comment. I wish I didn't have to display all the dates for which data is not available, to reduce the blank space... Maybe by discontinuing the x-axis.. – Mayou Nov 15 '13 at 15:08
  • 1
    I have never used a discontinuous x-axis in `zoo` plots, and I doubt it is possible. You may wish to have a look at `gap.plot` in the `plotrix` package, or perhaps try faceting in `ggplot2`. – Henrik Nov 15 '13 at 15:12
  • 1
    @Mariam, please note that I updated to `seq(month(min(d)) - 1`. From `?yearmon`: "The "yearmon" class [...] holds the data as year plus 0 for January". So now `tt` runs from "jan 2007". – Henrik Nov 15 '13 at 16:23
0

Change vec to following:

vec <- c(runif(5, 0.5, 0.7), NA, NA, NA, runif(5, 0.5, 0.7))

To have breaks, dates corresponding to vec must have NA values, if there is no data for that date then break.

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • 1
    Well, this means that I have to create an index with all the dates, rather than just the dates for which I have data, and then fill the vector with NAs. Not very convenient... – Mayou Nov 15 '13 at 15:00
  • using `seq()` together with `merge()` it should be easy, but agree still not very convenient. – zx8754 Nov 15 '13 at 15:05