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()
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()
I can solve the problem by manually creating an interaction column and group
ing by that:
d$interact <- interaction(d$replicate, d$treatment)
ggplot(d, aes(x=x, y=y, colour=treatment, group=interact)) +
geom_point() + geom_line()
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.