0

I've got an incomplete timeseries meaning that there is a big gap in the observations:

dat <- data.frame(
  date = c(2000, 2001, 2002, 2009, 2010, 2011),
  value1 = runif(6,1,100),
  value2 = runif(6,1,100)
)
library("reshape2")
dat_long <- melt(dat, id="date")
dat_long$time <- ifelse(dat_long$date < 2009, "early", "late")

I would like to plot dat using ggplot2, but with a gap between the observations 2002 and 2009. Effectively, there shall be two group of lines: One for 2000, 2001 and 2002, and the other one for 2009, 2010 and 2011 (hence, grouped by time).

According Line break when no data in ggplot2, I tried

library("ggplot2")
ggplot(data=dat_long, aes(x=date, y=value, group=variable)) +
  geom_line(aes(color=variable, group=time)) +
  geom_point(aes(color=variable))

But this simply combines all the points:

All points combined

The difference between my question and Line break when no data in ggplot2 is that I have multiple lines, which obviously prohibits the use of group=time in my geom_line(aes(...)) call.

Then I tried facets as a second-best solution:

ggplot(data=dat, aes(x=date, y=value, group=variable)) +
  geom_line() + geom_point() + facet_grid( ~ time)

But this draws the entire scale along the x axis even though there are no observations: Facet

Community
  • 1
  • 1
MERose
  • 4,048
  • 7
  • 53
  • 79
  • 1
    Try `ggplot(data=merge(x = data.frame(data_date = seq(min(dat[, 1]), max(dat[, 1]))), y = dat, all.x = TRUE), aes(x=data_date, y=data_value)) + geom_line() + geom_point()`. – lukeA Aug 21 '15 at 19:42
  • 3
    You could add `scales = "free_x"` to your `facet_grid` call. – nrussell Aug 21 '15 at 19:43
  • Isn't there even a package especially for plots from data that has a gap in it? – maj Aug 21 '15 at 19:44
  • 1
    @maj There is `gap.plot` from the `plotrix` package, see [here](http://www.inside-r.org/packages/cran/plotrix/docs/gap.plot). – RHA Aug 22 '15 at 10:43

1 Answers1

1

You could use a new variable for grouping equal to variable+time (i.e. four groups : value1-early, value1-late, value2-early,value2-late)

dat_long$gr <- with(dat_long,paste0(variable,time))

ggplot(data=dat_long, aes(x=date, y=value, group=gr,color=variable)) +
  geom_line() +
  geom_point()

enter image description here

scoa
  • 19,359
  • 5
  • 65
  • 80