Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot two lines in ggplot2

Tags:

r

ggplot2

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?!

like image 567
Plsvn Avatar asked Mar 05 '11 01:03

Plsvn


1 Answers

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()
like image 188
Ista Avatar answered Nov 01 '22 12:11

Ista