`geom_line ()` connects points mapped to different groups

I would like to group my data based on the interaction of two variables, but only comparing aesthetics with one of these variables. (Another variable is replication, which theoretically should be equivalent to each other). I can find inelegant ways to do this, but there seems to be a more elegant way to do this.

for example

 # 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

This is almost all correct, except that I do not want to represent points with different shapes. It seems that group=interaction(treatment, replicate) will help (for example, based on this question , but geom_line() still connects the points in different groups:

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

enter image description here

I can solve the problem by manually creating an interaction column and group using this:

 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

but it seems that there should be a more ggplot2 -native way to get geom_line only for connecting points from the same group.

+5
r ggplot2
03 Sep '13 at 18:18
source share
1 answer

Your code works if you do the following. I think you had a problem because aes handled "treat" and "replicate" as vectors, so it was equivalent to group = 1 .

 ggplot(d, aes(x=x, y=y, colour=treatment, group=interaction(treatment, replicate))) + geom_point() + geom_line() 
+5
Sep 03 '13 at 18:25
source share



All Articles