10

I'd like to group my data based on the interaction of two variables, but only map an aesthetic to one of those variables. (The other variable represents replicates which should, in theory, be equivalent to each other). I can find inelegant ways to do this, but it seems like there ought to be more elegant way to do it.

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 almost gets it right, except that I don't want to represent the points with different shapes. It seems like group=interaction(treatment, replicate) would help (e.g based on this question, but geom_line() still connects 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 grouping by that:

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 like there ought to be a more ggplot2-native way of getting geom_line to only connect points from the same group.

4

1 回答 1

11

Your code works if you do the following. I think you had a problem because aes treated "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()
于 2013-09-03T18:25:54.337 回答