在 ggplot2中按两列分组

有没有可能按两列分组呢? 这样就画出了横积 通过 geom_point()geom_smooth()

例如:

frame <- data.frame(
series <- rep(c('a', 'b'), 6),
sample <- rep(c('glass','water', 'metal'), 4),
data <- c(1:12))


ggplot(frame, aes()) # ...

Such that the points 6 and 12 share a group, but not with 3.

121991 次浏览

为什么不将这两列 paste放在一起并使用 那个变量作为组呢?

frame$grp <- paste(frame[,1],frame[,2])

更正式的方法是使用函数 interaction

例如:

 qplot(round, price, data=firm, group=id, color=id, geom='line') +
geom_smooth(aes(group=interaction(size, type)))

Taking the example from 这个问题, using interaction to combine two columns into a new factor:

# 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,
group=interaction(treatment, replicate))) +
geom_point() + geom_line()

ggplot example