Ggplot2: do not connect dots if time span

I have 4 time series but some years are missing.

When I draw them, non-consecutive years are connected.

enter image description here

I would like to link only consecutive years. How can i do this?

Here's an example of reproducibility:

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

      

+3


source to share


1 answer


You can connect 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()

      



enter image description here

+4


source







All Articles