简体   繁体   English

如何在ggplot2中绘制两条线

[英]How to plot two lines in 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. 这似乎与Hadley在其ggplot2书中的一些示例相似,但是我似乎无法完成这项工作。 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. 我认为这应该绘制这8个点,并在col = 1的情况下通过前四个点画一条线,在col = 2的情况下通过后四个点画另一条线。但是我最后得到的是一条红色和蓝色线段交替的线。

Why?! 为什么?!

Because col is numeric. 因为col是数字。 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, 您可以将col更改为一个因子,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM