How do I place an identical smooth on each facet of a ggplot2 object?

前端 未结 1 1521
面向向阳花
面向向阳花 2020-12-11 21:18

Here\'s an example:

eg <- data.frame(x = c(1:50, 50:1),  
                 y = c(1:50, 1:50) + rnorm(100),  
                 g = rep(c(\"a\",\"b\"), eac         


        
相关标签:
1条回答
  • 2020-12-11 21:49

    Clever trick: setting the faceting variable to NULL

    library(ggplot2)
    eg <- data.frame(x = c(1:50, 50:1),  
                     y = c(1:50, 1:50) + rnorm(100),  
                     g = rep(c("a","b"), each=50))  
    
    p <- qplot(x, y, data = eg) +  
      facet_wrap(~ g) +  
      geom_smooth()
    
    p + geom_smooth(data=within(eg, g <- NULL), fill="red")
    

    Or if you prefer, use facet_grid(..., margins=TRUE):

    p + facet_grid(.~g, margins=TRUE)
    
    0 讨论(0)
提交回复
热议问题