group by two columns in ggplot2

后端 未结 3 1403
遥遥无期
遥遥无期 2020-12-01 00:09

Is it possible to group by two columns? So the cross product is drawn by geom_point() and geom_smooth()?

As example:

frame          


        
相关标签:
3条回答
  • 2020-12-01 00:18

    Why not just paste those two columns together and use that variable as groups?

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

    A somewhat more formal way to do this would be to use the function interaction.

    0 讨论(0)
  • 2020-12-01 00:18

    Taking the example from this question, 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

    0 讨论(0)
  • 2020-12-01 00:31

    for example:

     qplot(round, price, data=firm, group=id, color=id, geom='line') +  
          geom_smooth(aes(group=interaction(size, type)))
    
    0 讨论(0)
提交回复
热议问题