0%

corrplot绘制相关性图

总结在R中使用corrplot绘制相关性图。

1. 加载数据

1
2
3
4
5
6
7
8
9
10
# 加载数据,数据需转换成矩阵
data(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

2. 计算相关性系数

corrpolt用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
corrplot(
corr,
method = c("circle", "square", "ellipse", "number", "shade", "color", "pie"),
type = c("full", "lower", "upper"),
col = NULL,
col.lim = NULL,
bg = "white",
title = "",
is.corr = TRUE,
add = FALSE,
diag = TRUE,
outline = FALSE,
mar = c(0, 0, 0, 0),
addgrid.col = NULL,
addCoef.col = NULL,
addCoefasPercent = FALSE,
order = c("original", "AOE", "FPC", "hclust", "alphabet"),
hclust.method = c("complete", "ward", "ward.D", "ward.D2", "single", "average",
"mcquitty", "median", "centroid"),
addrect = NULL,
rect.col = "black",
rect.lwd = 2,
tl.pos = NULL,
tl.cex = 1,
tl.col = "red",
tl.offset = 0.4,
tl.srt = 90,
cl.pos = NULL,
cl.length = NULL,
cl.cex = 0.8,
cl.ratio = 0.15,
cl.align.text = "c",
cl.offset = 0.5,
number.cex = 1,
number.font = 2,
number.digits = NULL,
addshade = c("negative", "positive", "all"),
shade.lwd = 1,
shade.col = "white",
p.mat = NULL,
sig.level = 0.05,
insig = c("pch", "p-value", "blank", "n", "label_sig"),
pch = 4,
pch.col = "black",
pch.cex = 3,
plotCI = c("n", "square", "circle", "rect"),
lowCI.mat = NULL,
uppCI.mat = NULL,
na.label = "?",
na.label.col = "black",
win.asp = 1,
...
)
1
M <- cor(mtcars)

3. 绘图

展示方式:

1
corrplot(M)

alt 图标

1
corrplot(M,method="number")

alt 图标

1
corrplot(M,method="color")

alt 图标

method还有其他选项:square、shade、pie、ellipse等。

排序:

1
corrplot(M,order = "hclust")

alt 图标

1
corrplot(M,order = "AOE")

alt 图标

添加相关性系数数值:

1
corrplot(M,order = "hclust",addCoef.col = "grey")

alt 图标

添加聚类框:

1
corrplot(M, order = "hclust",addrect = 2,rect.col='red')

alt 图标

修改颜色:

1
corrplot(M, order = "hclust",tl.col='black')

alt 图标

设置展示类型

type可以选upper、lower、full。

1
corrplot(M, order = "hclust", type='upper')

alt 图标

4. pvalue不显著的不显示

1
2
3
# 先进行显著性检验
corrl <- cor.mtest(mtcars)
corrplot(M, order = "hclust", p.mat = corrl$p)

默认的会对不显著的打叉:
alt 图标

添加insig参数,指定不显著的为空

1
corrplot(M, order = "hclust", p.mat = corrl$p,insig = "blank")

alt 图标

显示pvalue的*。

1
2
3
4
corrplot(M, order = "hclust", 
p.mat = corrl$p,insig='label_sig',
sig.level = c(0.001,0.01,0.05),
pch.cex = 0.9,pch.col = 'green')

alt 图标

以上是corrplot主要功能。注意,corrplot包只适用于正方形,也就是说横向和纵向一样的去比较。