Scatterplot Matrix in ggplot2

How to make Scatterplot Matrix using `ggpairs()` in ggplot2 with Plotly.


New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Default splot plot

The ggpairs() function of the GGally package allows to build a great scatterplot matrix.

Scatterplots of each pair of numeric variable are drawn on the left part of the figure. Pearson correlation is displayed on the right. Variable distribution is available on the diagonal.

library(plotly)
library(GGally)

data <- data.frame( var1 = 1:100 + rnorm(100,sd=20), v2 = 1:100 + rnorm(100,sd=27), v3 = rep(1, 100) + rnorm(100, sd = 1)) 
data$v4 = data$var1 ** 2 
data$v5 = -(data$var1 ** 2) 

p <- ggpairs(data, title="correlogram with ggpairs()") 

ggplotly(p)

Visualize correlation

he ggcorr() function allows to visualize the correlation of each pair of variable as a square. Note that the method argument allows to pick the correlation type you desire.

library(plotly)
library(GGally)

data <- data.frame( var1 = 1:100 + rnorm(100,sd=20), v2 = 1:100 + rnorm(100,sd=27), v3 = rep(1, 100) + rnorm(100, sd = 1)) 
data$v4 = data$var1 ** 2 
data$v5 = -(data$var1 ** 2) 

p <- ggcorr(data, method = c("everything", "pearson")) 

p

Split by group

It is possible to use ggplot2 aesthetics on the chart, for instance to color each category.

library(plotly)
library(GGally)

data(flea)

p <- ggpairs(flea, columns = 2:4, ggplot2::aes(colour=species)) 

ggplotly(p)