5

This seems to be a similar example to some of Hadley's examples in his ggplot2 book, but I can't seem to make this work. Given:

off = c(0, 2000, 4000, 6000, 25, 3000, 6050, 9000)
tim = c( 0, -100, -200, -300 -25, -125, -225, -325)
col = c( 1, 1, 1, 1, 2, 2, 2, 2)
dataf = data.frame(off, tim, col)
p = ggplot(dataf, aes(off, tim, color=col)) + geom_point() + geom_line()
p

I think this should plot these eight points and draw ONE line through the first four points with col = 1 and another line through the last four points with col = 2. Yet what I end up with is one line with alternating red and blue segments.

Why?!

1 Answer 1

6

Because col is numeric. Grouping is set to the interaction of factor variables, but since there are none the line is plotted as a single group. You can either change col to a factor,

ggplot(datf, aes(off, tim, color=factor(col))) + geom_point() + geom_line()

or manually set the grouping

ggplot(datf, aes(off, tim, color=col, group=col)) + geom_point() + geom_line()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ista, this does the trick and explains some things I didn't pick up from Hadley's book.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.