Various Scatterplots

Scatterplot을 그리는 여러가지 방법에 대해서 설명하겠습니다.

  1. pairs() function을 이용

  2. {ggplot2} package를 이용

  3. {PerformanceAnalytics} package를 이용해서 Scatterplot을 그리는 다양한 방법에 대해서 설명하겠습니다.

특히 {PerformanceAnalytics} package는 Scatterplot 안에 여러 정보를 한눈에 보기 쉽게 그려주는 매우 유용한 package가 되겠습니다.

data(iris)

# Load the iris dataset

간단하게 R에서 기본적으로 제공되는 iris data set을 가지고 살펴보겠습니다.

1. Scatterplot using pairs function

첫번째로 paris() function을 이용해서 간단한 Scatterplot을 만드는 code입니다.

pairs(~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris)

plot of chunk unnamed-chunk-2

2. Scatterplot using {ggplot2}

두번째로 {ggplot2} package의 plotmatrix() function을 이용해서 산포뿐만 아니라 density도 함께 보여주는 Plot입니다.

library(ggplot2)

plotmatrix(with(iris, data.frame(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width)))

plot of chunk unnamed-chunk-3

3. Scatterplot using {PerformanceAnalytics}

세번째로 {PerformanceAnalytics} package의 chart.Correlation() function입니다.

이 function은 데이터의 산포, 히스토그램, 상관계수등을 하나의 Plot안에 모두 나타내 주는 유용한 기능을 가지고 있습니다.

library(PerformanceAnalytics)
library(xts)
library(zoo)

mydata <- iris[, 1:4]
chart.Correlation(mydata)

plot of chunk unnamed-chunk-4

chart.Correlation과 같은 비슷한 결과물을 1.에서 살펴본 paris() function으로도 만들 수 있습니다. 다만, user-defiend function을 만들어야 하는 번거로움이 있습니다.

4. User-defined function : paris() like chart.Correlation() function

panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...) {
    usr <- par("usr")
    on.exit(par(usr))
    par(usr = c(0, 1, 0, 1))
    r <- abs(cor(x, y))
    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 * r)
}

# user-defined function

pairs(~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris, 
    lower.panel = panel.smooth, upper.panel = panel.cor, pch = 20, main = "Iris Scatter Matrix")

plot of chunk unnamed-chunk-5

이와 같이 사용자가 정의한 함수를 이용해 paris() function으로도 chart.Correlation() function과 유사한 scatter matrix를 만들 수 있습니다.

하지만 user-defined function을 만들기가 번거롭기 때문에 {PerformanceAnalytics} package의 chart.Correlation() function의 기능은 매우 유용합니다.


Hankuk University of Foreign Studies. Dept of Statistics. Daewoo Choi Lab. Yong Cha.
한국외국어대학교 통계학과 최대우 교수 연구실 차용
e-mail : yong.stat@gmail.com