0

I need to create a ggplot time series chart with one line where the colour of the line depends on a binary factor variable. Somehow my code generates two lines when I colour by factor:

date = seq(as.Date("2018-01-01"), as.Date("2018-01-20"), by = 1)
data = rnorm(20)
factor = as.factor(sample(0:1,20,replace=T))
df = data.frame(date = date, data = data, factor = factor)

p=ggplot(df, aes(date))
p=p + geom_line(aes(y = data, colour = factor))
print(p)

How can I fix the problem?

kanimbla
  • 858
  • 1
  • 9
  • 23
  • 3
    Set group to 1, i.e. `aes(y = data, colour = factor, group = 1)`. ggplot is trying to be helpful here, and set your grouping automatically (this is what you would usually want), but since you want only a single group you need to set it back to 1. – Axeman Oct 04 '18 at 10:46
  • This was easy :-) Do you want to post it as an answer? – kanimbla Oct 04 '18 at 10:48
  • I'm 90% sure it's a duplicate, but I don't have time to find the correct target right now. – Axeman Oct 04 '18 at 10:50
  • I was also sure to find it somewhere, but so far I did not. If it's a duplicate I am happy to close the question... – kanimbla Oct 04 '18 at 10:54

0 Answers0