Chapter 8 Default Scatter Plot Matrices in R
Scatter Plot Matrices:
par(mfrow=c(2,1))
pairs(~mpg+disp+drat+wt,data=mtcars,
main="Simple Scatterplot Matrix")
pairs(~mpg+disp+drat+wt,data=mtcars,lower.panel = NULL,
main="Simple Scatterplot Matrix")
Color points by groups Scatter plots:
my_col <- c("#00AFBB", "#E7B800", "#FC4E07")
pairs(iris[,1:4], pch = 19, cex = 0.5,
col = my_col[iris$Species],
lower.panel=NULL)
Add correlations on the lower panels:
# Correlation panel
my_col <- c("#00AFBB", "#E7B800", "#FC4E07")
panel.cor <- function(x, y){
usr <- par("usr"); on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
r <- round(cor(x, y), digits=2)
txt <- paste0("R = ", r)
cex.cor <- 0.8/strwidth(txt)
text(0.5, 0.5, txt, cex = cex.cor * r)
}
# Customize upper panel
upper.panel<-function(x, y){
points(x,y, pch = 19, col = my_col[iris$Species])
}
# Create the plots
pairs(iris[,1:4],
lower.panel = panel.cor,
upper.panel = upper.panel)
Add correlations on the scatter plots:
my_col <- c("#00AFBB", "#E7B800", "#FC4E07")
# Customize upper panel
upper.panel<-function(x, y){
points(x,y, pch=19, col=c("red", "green3", "blue")[iris$Species])
r <- round(cor(x, y), digits=2)
txt <- paste0("R = ", r)
usr <- par("usr"); on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
text(0.5, 0.9, txt)
}
pairs(iris[,1:4], lower.panel = NULL,
upper.panel = upper.panel)
Additional-> the R package psych:
#install.packages("psych")
library(psych)
##
## Attaching package: 'psych'
## The following object is masked from 'package:car':
##
## logit
pairs.panels(iris[,-5],
method = "pearson", # correlation method
hist.col = "#52E932",
density = TRUE, # show density plots
ellipses = TRUE # show correlation ellipses
)