在ggplot2中按两列分组

Rea*_*onk 82 r 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()) # ...
Run Code Online (Sandbox Code Playgroud)

这样点612分享一组,但没有3.

Blu*_*ter 148

这个问题为例,使用interaction将两列组合成一个新因子:

# 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()
Run Code Online (Sandbox Code Playgroud)

ggplot的例子

  • 真好 这应该是公认的答案。 (3认同)

Dav*_*jad 57

例如:

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


jor*_*ran 30

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

frame$grp <- paste(frame[,1],frame[,2])
Run Code Online (Sandbox Code Playgroud)

一种更正式的方法是使用该功能interaction.

  • 我认为你不应该为了一个情节修改你的`data.frame`.`plot`应该绘制你的df而不是相反的. (23认同)
  • @clemlaflemme我认为BlueMagister的答案很好,虽然我认为在这种情况下的区别很小.但是,如果你选择使用**ggplot2**,那么人们不应该修改你的数据框的一般位置是好奇的,其整个设计的前提是明确地构造你的数据以使用ggplot的语义. (6认同)
  • 我同意,Blue Magister的答案更好。 (2认同)