소개

corrplot 패키지는 상관행렬(correlation matrix)와 신뢰구간(confidence interval)의 그래프이다. 또한 행렬의 재정렬(reordering) 알고리즘을 포함하고 있으며 색의 선택, 텍스트 라벨링, 칼라 라벨등을 포함하고 있다.

Visualization Methods

패키지에 포함되어 있는 방법은 모두 7가지가 있다. circle, square,ellipse,number,shade,color,pie의 7가지이다. 패키지의 설명을 위해 corrplot 라이브러리를 불러오고 mtcars 데이타를 불러온다. cor(mtcars)를 M이라는 행렬에 저장한다.

library(corrplot)
M<-cor(iris[,1:4])
M
             Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length       1.0000     -0.1176       0.8718      0.8179
Sepal.Width       -0.1176      1.0000      -0.4284     -0.3661
Petal.Length       0.8718     -0.4284       1.0000      0.9629
Petal.Width        0.8179     -0.3661       0.9629      1.0000

다음은 corrplot의7가지 방법이다.

corrplot(M,method="circle")

plot of chunk unnamed-chunk-2

corrplot(M,method="square")

plot of chunk unnamed-chunk-2

corrplot(M,method="ellipse")

plot of chunk unnamed-chunk-2

corrplot(M,method="number")

plot of chunk unnamed-chunk-2

corrplot(M,method="shade")

plot of chunk unnamed-chunk-2

corrplot(M,method="color")

plot of chunk unnamed-chunk-2

corrplot(M,method="pie")

plot of chunk unnamed-chunk-2

Layout

layout은 세가지가 있는데 “full”(디폴트)“,”upper“,”lower“이다.

corrplot(M,type="upper")

plot of chunk unnamed-chunk-3

corrplot(M,type="lower")

plot of chunk unnamed-chunk-3

corrplot.mixed 함수는 시각화방법을 혼합할때 사용한다.

corrplot.mixed(M)

plot of chunk unnamed-chunk-4

corrplot.mixed(M,lower="ellipse",upper="circle")

plot of chunk unnamed-chunk-4

corrplot.mixed(M,lower="square",upper="circle")

plot of chunk unnamed-chunk-4

상관계수행렬의 재정렬

행렬의 재정렬은 행렬의 숨겨진 구조나 패턴을 찾는데 매우 중요하다. corrplot 패키지에는 네가지 방법(parametric order)이 있는데 AOE, FPC, hclust, alphbetic의 네가지이며 seriation 패키지에는 보다 많은 알고리즘이 포함되어 있다. 또한 corrMatOrder() 함수를 사용하는 경우 행렬을 수동으로 재정렬할수 있다.

corrplot(M,order="AOE")

plot of chunk unnamed-chunk-5

corrplot(M,order="hclust")

plot of chunk unnamed-chunk-5

corrplot(M,order="FPC")

plot of chunk unnamed-chunk-5

corrplot(M,order="alphabet")

plot of chunk unnamed-chunk-5

“hclust”를 사용한 경우 계층적군집의 결과에 따라 상관행렬의 주위에 사각형을 그릴수 있다.

corrplot(M,order="hclust",addrect=2)

plot of chunk unnamed-chunk-6

corrplot(M,order="hclust",addrect=3)

plot of chunk unnamed-chunk-6

다른 스펙트럼의 색 사용

다른 color system을 사용할때 colorRampPalette()함수를 사용하면 매우 편리하다

col1 <- colorRampPalette(c("#7F0000", "red", "#FF7F00", "yellow", "white", "cyan", 
    "#007FFF", "blue", "#00007F"))
col2 <- colorRampPalette(c("#67001F", "#B2182B", "#D6604D", "#F4A582", "#FDDBC7", 
    "#FFFFFF", "#D1E5F0", "#92C5DE", "#4393C3", "#2166AC", "#053061"))
col3 <- colorRampPalette(c("red", "white", "blue"))
col4 <- colorRampPalette(c("#7F0000", "red", "#FF7F00", "yellow", "#7FFF7F", 
    "cyan", "#007FFF", "blue", "#00007F"))
wb <- c("white", "black")
## using these color spectrums
corrplot(M, order = "hclust", addrect = 2, col = col1(100))

plot of chunk unnamed-chunk-7

corrplot(M, order = "hclust", addrect = 2, col = col2(50))

plot of chunk unnamed-chunk-7

corrplot(M, order = "hclust", addrect = 2, col = col3(20))

plot of chunk unnamed-chunk-7

corrplot(M, order = "hclust", addrect = 2, col = col4(10))

plot of chunk unnamed-chunk-7

corrplot(M, order = "hclust", addrect = 2, col = wb, bg="gold2")

plot of chunk unnamed-chunk-7

색깔 및 텍스트 설명문

함수의 인수들 중 cl.로 시작하는 인수는 color legend, tl.로 시작하는 인자는 text legend를 뜻한다.
몇가지 예를 들어보면 다음과 같다.

# color legend 및 text legend 제거 
corrplot(M,order="AOE",cl.pos="n",tl.pos="n")

plot of chunk unnamed-chunk-8

# color legend를 밑으로(bottom), text를 대각선으로 , text label의 회전
corrplot(M,order="AOE",cl.pos="b",tl.pos="d",tl.srt=60)

plot of chunk unnamed-chunk-8

# color legend를 더 넓게 오른쪽으로 
corrplot(M,order="AOE",cl.ratio=0.2, cl.pos="r")

plot of chunk unnamed-chunk-8

상관행렬이 아닌 행렬의 경우

corrplot(abs(M), order = "AOE", col = col3(200), cl.lim = c(0, 1))

plot of chunk unnamed-chunk-9

## visualize a matrix in [-100, 100]
ran <- round(matrix(runif(225, -100, 100), 15))
corrplot(ran, is.corr = FALSE, method = "square")

plot of chunk unnamed-chunk-9

## a beautiful color legend
corrplot(ran, is.corr = FALSE, method = "ellipse", cl.lim = c(-100, 100))

plot of chunk unnamed-chunk-9

유의성 검정과 함께 사용하기

cor.mtest <- function(mat, conf.level = 0.95) {
    mat <- as.matrix(mat)
    n <- ncol(mat)
    p.mat <- lowCI.mat <- uppCI.mat <- matrix(NA, n, n)
    diag(p.mat) <- 0
    diag(lowCI.mat) <- diag(uppCI.mat) <- 1
    for (i in 1:(n - 1)) {
        for (j in (i + 1):n) {
            tmp <- cor.test(mat[, i], mat[, j], conf.level = conf.level)
            p.mat[i, j] <- p.mat[j, i] <- tmp$p.value
            lowCI.mat[i, j] <- lowCI.mat[j, i] <- tmp$conf.int[1]
            uppCI.mat[i, j] <- uppCI.mat[j, i] <- tmp$conf.int[2]
        }
    }
    return(list(p.mat, lowCI.mat, uppCI.mat))
}

res1 <- cor.mtest(mtcars, 0.95)
res2 <- cor.mtest(mtcars, 0.99)
## 유의수준에 따라 유의하지 않은 경우 X 표시하기
corrplot(M, p.mat = res1[[1]], sig.level = 0.2)

plot of chunk unnamed-chunk-10

corrplot(M, p.mat = res1[[1]], sig.level = 0.05)

plot of chunk unnamed-chunk-10

corrplot(M, p.mat = res1[[1]], sig.level = 0.01)

plot of chunk unnamed-chunk-10

## 유의하지 않을 경우 빈칸으로 남기기
corrplot(M, p.mat = res1[[1]], insig = "blank")

plot of chunk unnamed-chunk-10

## 유의하지 않은 경우 p값 쓰기
corrplot(M, p.mat = res1[[1]], insig = "p-value")

plot of chunk unnamed-chunk-10

## p값 모두 쓰기
corrplot(M, p.mat = res1[[1]], insig = "p-value", sig.level = -1)

plot of chunk unnamed-chunk-10

## 유의하지 않은 경우 X 표시하기
corrplot(M, p.mat = res1[[1]], order = "hclust", insig = "pch", addrect = 3)

plot of chunk unnamed-chunk-10

## r value를 쓰고 유의하지 않은 경우 x표시하기
corrplot.mixed(M,lower="color",upper="number",p.mat=res1[[1]],sig.level=0.05)

plot of chunk unnamed-chunk-10

다음은 r value를 쓰고 유의하지 않은 경우 x표시하기, p-value 쓰기

corrplot.mixed(M,lower="color",upper="number",p.mat=res1[[1]],sig.level=0.05)
l=length(M[1,])
for(i in 1:l)
    for(j in 1:l)
    {
        if(i >= j) next
        text(i,l-j+1,round(res1[[1]][i,j],2))
    }

plot of chunk unnamed-chunk-11

p-value에 따라 r-value에 *,** 덧붙여 그림에 넣기

result=round(M,2)
result
##              Sepal.Length Sepal.Width Petal.Length Petal.Width
## Sepal.Length         1.00       -0.12         0.87        0.82
## Sepal.Width         -0.12        1.00        -0.43       -0.37
## Petal.Length         0.87       -0.43         1.00        0.96
## Petal.Width          0.82       -0.37         0.96        1.00
l=length(M[1,])
for(i in 1:l)
{
    for(j in 1 :l)
    {
        result[i,j]=ifelse(res1[[1]][i,j]>=0.05,paste(result[i,j],"",sep=""),
                           ifelse(res1[[1]][i,j]>=0.01,paste(result[i,j],"*",sep=""),
                                  paste(result[i,j],"**",sep="")))
                                  
    }
}
result
##              Sepal.Length Sepal.Width Petal.Length Petal.Width
## Sepal.Length "1**"        "-0.12**"   "0.87**"     "0.82**"   
## Sepal.Width  "-0.12**"    "1**"       "-0.43**"    "-0.37**"  
## Petal.Length "0.87**"     "-0.43**"   "1**"        "0.96**"   
## Petal.Width  "0.82**"     "-0.37**"   "0.96**"     "1**"
corrplot.mixed(M,lower="color",upper="number",p.mat=res1[[1]],sig.level=0.05)
l=length(M[1,])
for(i in 1:l)
    for(j in 1:l)
    {
        if(i >= j) next
        text(i,l-j+1,result[i,j])
    }

plot of chunk unnamed-chunk-12

신뢰구간의 시각화

## plot confidence interval(0.95, 0.95, 0.99), 'rect' method
corrplot(M, low = res1[[2]], upp = res1[[3]], order = "hclust", rect.col = "navy", 
    plotC = "rect", cl.pos = "n")

plot of chunk unnamed-chunk-13

corrplot(M, p.mat = res1[[1]], low = res1[[2]], upp = res1[[3]], order = "hclust", 
    pch.col = "red", sig.level = 0.01, addrect = 3, rect.col = "navy", 
    plotC = "rect", cl.pos = "n")

plot of chunk unnamed-chunk-13