对 ggplot2 中的分组点感到困惑

confused about grouping points in ggplot2

为什么此代码不在具有相同 y 值的数据之间划线?

main <- data_frame(x=rep(c(-1, 1), each=2), y = c(c(1, 1), c(2, 2)), z = c(1, 2, 3, 4))
qplot(data = main, x = x, y = z, geom="line", group=factor(y))

这是我得到的:

但我只想连接与y相同级别的点。

问题在于您定义 y 变量的方式。将其更改为 y = c(c(1,2), c(1,2)) 一切正常。

此外,如果您要使用 data_frame,请务必添加对 library 的调用以使您的代码可重现(即 library(dplyr)library(ggplot2) ).