Reputation:
I have 4 time series but some years are missing.
When I plot them the non consecutive years are connected.
I'd like to only connect consecutive years. How could I do that ?
Here is an reproducible example:
set.seed(1234)
data <- data.frame(year=rep(c(2005,2006,2010, 2011 ),5),
value=rep(1:5,each=4)+rnorm(5*4,0,5),
group=rep(1:5,each=4))
data
ggplot(data, aes(x= year, y= value, group= as.factor(group), colour= as.factor(group))) +
geom_line()
Upvotes: 4
Views: 1613
Reputation: 25608
You can plug in NA
, and ggplot
will do exactly what you want.
# generate all combinations of year/group
d <- expand.grid(min(data$year):max(data$year), unique(data$group))
# fill NA if combination is missing
d$val <- apply(d, 1,
function(x) if (nrow(subset(data, year == x[1] & group == x[2]))) 0 else NA)
# modify the original dataset
names(d) <- c("year", "group", "value")
data <- rbind(data, d[is.na(d$val), ])
ggplot(data, aes(x=year, y=value,
group=as.factor(group), colour=as.factor(group))) + geom_line()
Upvotes: 6