开发者

How to plot two lines in ggplot2

开发者 https://www.devze.com 2023-02-14 18:45 出处:网络
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.

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(开发者_C百科) + 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?!


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

精彩评论

暂无评论...
验证码 换一张
取 消