`geom_line()`连接映射到不同组的点

时间:2013-09-03 18:18:26

标签: r ggplot2

我想根据两个变量的相互作用group我的数据,但只将美学映射到其中一个变量。 (另一个变量代表重复,理论上它们应该相互等同)。我可以找到不太优雅的方法来做到这一点,但似乎应该有更优雅的方式去做。

例如

# Data frame with two continuous variables and two factors 
set.seed(0)
x <- rep(1:10, 4)
y <- c(rep(1:10, 2)+rnorm(20)/5, rep(6:15, 2) + rnorm(20)/5)
treatment <- gl(2, 20, 40, labels=letters[1:2])
replicate <- gl(2, 10, 40)
d <- data.frame(x=x, y=y, treatment=treatment, replicate=replicate)

ggplot(d, aes(x=x, y=y, colour=treatment, shape=replicate)) + 
  geom_point() + geom_line()

enter image description here

这几乎是正确的,除了我不想用不同形状表示点。似乎group=interaction(treatment, replicate)会有所帮助(例如基于this question,但geom_line()仍会连接不同群组中的点:

ggplot(d, aes(x=x, y=y, colour=treatment, group=interaction("treatment", "replicate"))) + 
  geom_point() + geom_line()

enter image description here

我可以通过手动创建交互列并group来解决问题:

d$interact <- interaction(d$replicate, d$treatment)

ggplot(d, aes(x=x, y=y, colour=treatment, group=interact)) + 
  geom_point() + geom_line()

enter image description here

但似乎应该有更ggplot2本地方式让geom_line只能连接来自同一组的点。

1 个答案:

答案 0 :(得分:5)

如果您执行以下操作,则代码可以正常运行。我认为您遇到了问题,因为aes"treat""replicate"视为向量,因此它等同于group = 1

ggplot(d, aes(x=x, y=y, colour=treatment, group=interaction(treatment, replicate))) + 
  geom_point() + geom_line()