相关分析之精彩的绘图展示

本文来展示R包”corrplot”对变量进行相关分析后能够给出的精彩图片,发表级。

数据采用mtcars:

head(mtcars)
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

绘图展示

下面这个图是其中可以展示的比较好看的一个

#if(!library(corrplot)) install.packages("corrplot")
library(corrplot)
## corrplot 0.92 loaded
M <- cor(mtcars)
corrplot(M, order="original",type = "upper",tl.pos = "tp")
corrplot(M, add = TRUE, type = 'lower', method = 'number', order = 'original',
         diag = FALSE, tl.pos = 'n', cl.pos = 'n')

在没有显著性相关的变量上面加上 p值

testRes = cor.mtest(mtcars, conf.level = 0.95)
corrplot(M, p.mat = testRes$p, insig = 'p-value')

其他好看的结果图片,可以用example(corrplot)展示。


请留意,如果想做spearman相关分析,cor()中可以定义 method="spearman",对于一些有缺失值的数据来说,可以定义函数忽略缺失值cor(mtcars,dc,method = "spearman",use = "complete.obs"),否则的话结果中会有很多‘?’出来。

另外,如果变量数比较多,比如100个变量,那么最终结果呈现时会比较杂乱,可以设定tl.cex=0.5,在画图时最好选择这个,因为数值不会显示出来:corrplot(M, order="original",tl.cex = 0.6)这样图中变量名称的字体会缩小。 但是在保存图片时,还是记得设定一下pointsize = 9,不然保存后的图形中字体又变大了。

M <- cor(mtcars,method = "spearman",use = "complete.obs")
#jpeg("corrplot.jpeg",width = 18, height = 18,units = "cm",res = 600,pointsize = 9)

corrplot(M, order="original",tl.cex = 0.6)

#dev.off()

-完-