散點圖矩陣可以顯示矩陣數據兩兩之間的散點圖。
1. 最樸素的繪製方法,是用pairs.
#構建數據
subi=iris[,1:4]
#默認散點圖矩陣
pairs(subi)
散點圖矩陣可以分為上三角區塊, 對角線區塊, 下三角區塊,我們可以自定義每個區塊的函數,而且達到修改pairs繪圖效果的目的。
比如用以下方式:
panel.cor<-function(x,y,digits=2,prefix="r=",cex.cor,...){
usr <-par('usr')
on.exit(par(usr))
par(usr=c(0,1,0,1))
r<-cor(x,y,use="complete.obs")
txt<-format(c(r,0.123456789),digits=digits)[1]
txt<-paste(prefix,txt,sep="")
if(missing(cex.cor)) cex.cor<-0.8/strwidth(txt)
#text(0.5,0.5,txt,cex=cex.cor*(1+r)/2)
text(0.5,0.5,txt,cex=2)
}
panel.hist<-function(x,...){
usr<-par('usr')
on.exit(par(usr))
par(usr=c(usr[1:2],0,1.5))
h<-hist(x,plot=FALSE)
breaks<-h$breaks
nB<-length(breaks)
y<-h$counts
y<-y/max(y)
rect(breaks[-nB],0,breaks[-1],y,col="skyblue",...)
}
panel.lm<-function(x,y,col=par("col"),bg=NA,pch=par("pch"),
cex=2,col.smooth="black",...){
points(x,y,pch=pch,col=col,bg=bg,cex=cex)
abline(stats::lm(y~x),col=col.smooth,...)
}
pairs(subi,upper.panel=panel.cor,
diag.panel=panel.hist,
lower.panel=panel.lm,
pch=21,
bg =c("#1B9E77","#D95F02","#7570B3")[unclass(iris$Species)])
2. car包的scatterplotMatrix繪製
library(car)
scatterplotMatrix(~Sepal.Length+Sepal.Width+Petal.Length+Petal.Width,data=iris,
spread=FALSE,smooth=FALSE)
#優化一下
#顏色定義
library(RColorBrewer)
mycolor=brewer.pal(8,"Dark2")
col=as.vector(iris$Species)
col[col=='setosa']<-mycolor[1]
col[col=='versicolor']<-mycolor[2]
col[col=='virginica']<-mycolor[3]
scatterplotMatrix(~Sepal.Length+Sepal.Width+Petal.Length+Petal.Width,data=iris,
spread=FALSE,smooth=FALSE,groups=iris$Species,col=mycolor[1:3],pch=c(19,19,19))
3. 使用gclus包cpairs
library(gclus)
subiris=iris[,1:4]
mycorr=abs(cor(subiris))
mycolors <- dmat.color(mycorr)
myorder <- order.single(mycorr)
cpairs(subiris,myorder,panel.colors = mycolors,gap=.5,
main="Variables Ordered and Coloredby Correlation")
4. 用GGally包的ggpairs
library(GGally)
ggpairs(iris, aes(color=Species))+
theme_bw()
用於數據探索的話,這個很不錯。
下一講:三元圖