Search code examples
rggplot2ggpairs

ggpairs, color by group but single regression line


Given the following ggpairs plotting:

data(iris)
ggpairs(iris[1:4],
        lower=list(
          mapping = aes(color=iris$Species),
          continuous = wrap("points", size=0.7)
          )
        )

Which results in:
enter image description here

How can I add single regression lines to each of the scatter plots without the regression line also being mapped to the grouping as would occur when adding continuous = wrap("smooth")?

I would like the points to be colored by group but the regression line for the relationship between the x and y variable overall.

I can't figure out where to place the aes mapping so that it only affects 'points' and not 'smooth'.


Solution

  • You need to create your own function if you want specialized plots like this. It must be in a particular format, taking a data, mapping and ... argument, and create a ggplot from these:

    library(GGally)
    
    my_func <- function(data, mapping, ...) {
      
        ggplot(data, mapping) + 
          geom_point(size = 0.7) +
          geom_smooth(formula = y~x, method = loess, color = "black")
      }
    
    ggpairs(iris[1:4],
            lower=list(
              mapping = aes(color=iris$Species),
              continuous = my_func
              )
            )
    

    enter image description here

    If you are looking for a straight regression line, then just modify my_func as appropriate. For example,

    my_func <- function(data, mapping, ...) {
      
        ggplot(data, mapping) + 
          geom_point(size = 0.7) +
          geom_smooth(formula = y~x, method = lm, color = "black", se = FALSE,
                      linetype = 2)
      }
    

    Gives you:

    enter image description here