SlowLearner
SlowLearner

Reputation: 7997

R: prevent break in line showing time series data using ggplot geom_line

Using ggplot2 I want to draw a line that changes colour after a certain date. I expected this to be be simple, but I get a break in the line at the point the colour changes. Initially I thought this was a problem with group (as per this question; this other question also looked relevant but wasn't quite what I needed). Having messed around with the group aesthetic for 30 minutes I can't fix it so if anybody can point out the obvious mistake...

screenshot

Code:

require(ggplot2)

set.seed(1111)
mydf <- data.frame(mydate = seq(as.Date('2013-01-01'), by = 'day', length.out = 10),
    y = runif(10, 100, 200))
mydf$cond <- ifelse(mydf$mydate > '2013-01-05', "red", "blue")

ggplot(mydf, aes(x = mydate, y = y, colour = cond)) +
    geom_line() +
    scale_colour_identity(mydf$cond) +
    theme()

Upvotes: 2

Views: 1800

Answers (1)

Marius
Marius

Reputation: 60060

If you set group=1, then 1 will be used as the group value for all data points, and the line will join up.

ggplot(mydf, aes(x = mydate, y = y, colour = cond, group=1)) +
  geom_line() +
  scale_colour_identity(mydf$cond) +
  theme()

Upvotes: 5

Related Questions