How to add line fit on GGally correlation plot matrix

2.1k views Asked by At

The following plot

enter image description here

Is generated with the following code:

library(GGally)
dat <- read.csv("http://www.ats.ucla.edu/stat/data/tobit.csv")
ggpairs(dat[, c("read", "math", "apt")])

How can I add the correlation line for each of the scatter plot above?

2

There are 2 answers

2
user227710 On

Something like this?

ggpairs(dat[, c("read", "math", "apt")],lower = list(continuous = "smooth", params = c(method = "loess", fill = "blue"))

enter image description here

0
HBat On

You can customize the scatterplots in the lower triangle as you wish within a function like the one below:

library(GGally)
dat <- ggplot2::diamonds[1:1000, c("x", "y", "z")]  # Example data

# Customize your scatterplots as you wish here:
lowerfun <- function(data, mapping) {
  ggplot(data = data, mapping = mapping)+ 
    geom_point(alpha = .25) + 
    geom_smooth(method = "loess", formula = y ~ x, 
                fill = "blue", color = "red", size = 0.5)
}

# Plot the scatterplot matrix
ggpairs(dat, lower = list(continuous = wrap(lowerfun)))

enter image description here