How to use loess method in GGally::ggpairs using wrap function

One quick way is to write your own function... the one below was edited from the one provided by the ggpairs error message in your question

library(GGally)
library(ggplot2)    
data(swiss)

# Function to return points and geom_smooth
# allow for the method to be changed
my_fn <- function(data, mapping, method="loess", ...){
      p <- ggplot(data = data, mapping = mapping) + 
      geom_point() + 
      geom_smooth(method=method, ...)
      p
    }

# Default loess curve    
ggpairs(swiss[1:4], lower = list(continuous = my_fn))

enter image description here

# Use wrap to add further arguments; change method to lm
ggpairs(swiss[1:4], lower = list(continuous = wrap(my_fn, method="lm")))

enter image description here


This perhaps gives a bit more control over the arguments that are passed to each geon_

  my_fn <- function(data, mapping, pts=list(), smt=list(), ...){
              ggplot(data = data, mapping = mapping, ...) + 
                         do.call(geom_point, pts) +
                         do.call(geom_smooth, smt) 
                 }

# Plot 
ggpairs(swiss[1:4], 
        lower = list(continuous = 
                       wrap(my_fn,
                            pts=list(size=2, colour="red"), 
                            smt=list(method="lm", se=F, size=5, colour="blue"))))

Maybe you are taking the Coursera online course Regression Models and try to convert the Rmarkdown file given by the course to html file, and come across this error as I do.

The way I tried out is:

require(datasets); data(swiss); require(GGally); require(ggplot2)
g = ggpairs(swiss, lower = list(continuous = wrap("smooth", method = "lm")))
g

Also you can try using method="loess", but the outcome looks a bit different from that given in the lecture. method = "lm" may be a better fit as I see.


I suspected as well you were taking Coursera's class. Though, I could not find any github repo containing ggplot's examples.

Here's what I did to make it work:

gp = ggpairs(swiss, lower = list(continuous = "smooth"))
gp