基于R的相关性矩阵可视化
代码示例:
setwd("C:/Users/WEIX/Desktop/")
# 导入已计算好的相关性值
corr <- read.table(file = "data.txt",header = TRUE)
##转换为matrix
corr <- as.matrix(corr)
str(corr)
# 直接计算相关性值
data(mtcars)
##首先导入数据集mtcars
corr <- cor(mtcars)
##将数据集中的每个列的相关系数统计出来并保存在一个corr的参数中
library(corrplot)
corrplot(corr)
corrplot(corr,method="ellipse",shade.col=NA,tl.col="black",tl.srt=45)
library(GGally)
ggcorr(corr[,],
nbreaks=6,
low = "steelblue",
mid = "white",
high = "darkred",label= T)
corrplot方法
method参数:
#method参数主要包括以下几种:"circle", "square", "ellipse", "number", "shade", "color", "pie"
> par(mfrow=c(4,2))
> corrplot(corr,method="circle")
> corrplot(corr,method="square")
> corrplot(corr,method="ellipse")
> corrplot(corr,method="number")
> corrplot(corr,method="shade")
> corrplot(corr,method="color")
> corrplot(corr,method="pie")
label设置:
#颜色
tl.col="black",
#旋转角度
tl.srt=45
显著性:
#Combining correlogram with the significance test
res1 <- cor.mtest(mtcars, conf.level = .95)
res2 <- cor.mtest(mtcars, conf.level = .99)
## specialized the insignificant value according to the significant level
corrplot(M, p.mat = res1$p, sig.level = .2)