R 그래프를 그릴때 알아야 할 점

R의 가장 큰 강점은 그래프이다. 그래프는 용도에 따라 탐색적자료분석에 쓰이는 단순하고 멋 없는 그래프와 논문인쇄에 쓰이는 출판용 그래프로 나누어볼 수 있겠다.

먼저 R에 포함되어 있는 기본적인 그래프를 살펴보고 lattice 그래픽과 ggplot2 그래픽에 대한 소개를 하고자 한다.

그래프를 그리는 순서

1.그래프를 그릴 자료를 준비한다 2.고수준 그래프함수로 그래프를 그린다. 3.저수준 함수로 그래프를 장식한다 4.화일로 저장한다.

그래픽스 함수

그래프를 그리는 명령어 는 함수로 되어 있다. 함수를 호출하는 것이 그래프를 그리는 명령어이다. 이 함수는 고수준 함수와 저수준 함수로 되어 있다.

고수준 함수란? 저수준함수란?

자동차의 종류를 예를 들면 사람이 타는 승용차, 비포장길을 다니는 SUV, 화물을 실는 화물차 등이 있다. 이런 차의 종류를 뭉뚱그려 자동차라고 할 수 있다. 고수준 함수는 완성차와 같다. 고수준함수를 호출하면 현재 그래픽스창을 초기화 하고 새로운 그래프를 그린다. 제목과 장식등을 넣을 수도 있다. 하지만 경우에 따라 옵션을 추가한다던가 튜닝이 필요할 수 있다. 이런 역할을 하는 것이 저수준함수이다.

고수준 함수의 예는 plot, xyplot, boxplot, hist, coplot 등이 있다.

다형성이란 ?

그래프를 그리는 R의 기본 함수는 plot이다. 이것은 자동차와 같다. R의 plot함수는 다형성(ploymorphism)이 있다. 사람을 생각면서 자동차를 부르면 승용차가 나오고 화물을 생각하면서 자동차를 부르면 화물차가 나오는 식이다. plot함수에 무엇을 넘겨주느냐에 따라 xyplot이 나오기도 하고 boxplot이 나오기도 한다.

tail(mtcars)
##                 mpg cyl  disp  hp drat    wt qsec vs am gear carb
## Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.7  0  1    5    2
## Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.9  1  1    5    2
## Ford Pantera L 15.8   8 351.0 264 4.22 3.170 14.5  0  1    5    4
## Ferrari Dino   19.7   6 145.0 175 3.62 2.770 15.5  0  1    5    6
## Maserati Bora  15.0   8 301.0 335 3.54 3.570 14.6  0  1    5    8
## Volvo 142E     21.4   4 121.0 109 4.11 2.780 18.6  1  1    4    2
plot(mtcars)

plot of chunk unnamed-chunk-1

plot(mpg~disp, data=mtcars)

plot of chunk unnamed-chunk-1

plot(mpg~ factor(am),data=mtcars)

plot of chunk unnamed-chunk-1

coplot(mpg~disp | factor(am),data=mtcars)

plot of chunk unnamed-chunk-1

기본으로 점플롯이 만들어지지만(type=“p”) 선플롯(type=“l”)이나 점과 선으로된 플롯 (type=“b”)등을 선택할 수도 있다.

par(mfrow=c(1,3))
plot(1:10)
plot(1:10,type="l")
plot(1:10,type="b")

plot of chunk unnamed-chunk-2

par(mfrow=c(1,1))

점모양은 pch로 지정한다.(25가지), 점 크기는 cex로 조절한다

x=rep(1:5,each=5);x
##  [1] 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5
y=rep(5:1,5);y
##  [1] 5 4 3 2 1 5 4 3 2 1 5 4 3 2 1 5 4 3 2 1 5 4 3 2 1
plot(1:5,type="n",xlim=c(0,7.5),ylim=c(0,5.5))
points(x,y,pch=1:25,cex=2)
text(x-0.5,y,labels=as.character(1:25),cex=1.5)
points(rep(6,5),5:1,pch=65:69,cex=2)
text(rep(6,5)-0.5,5:1,labels=as.character(65:69),cex=1.5)
pchs=c("&","z","M","F","가")
points(rep(7,5),5:1,pch=pchs,cex=2,family="AppleGothic")
text(rep(7,5)-0.5,5:1,labels=pchs,cex=1.5,family="AppleGothic")

plot of chunk unnamed-chunk-3

기본 옵션을 선택하는 방법

그래프의 가장 기본적인 옵션은 제목, x축과 y축의 범위, 축이름, 색깔등이다. 다음 두 그래프를 비교해 보면

plot(mpg~disp,data=mtcars)

plot of chunk unnamed-chunk-4

plot(mpg~disp,data=mtcars,pch=21,col="black",bg=mtcars$am+2,cex=1.2,
     main="연비와 배기량",
     xlab="배기량(cu.in)",ylab="연비(mile per gallon)",
     xlim=c(0,500),ylim=c(0,40),family="AppleGothic")

plot of chunk unnamed-chunk-4

저수준 함수란?

저수준 함수는 새로운 그래프를 시작하는 것이 아니라 기존에 있는 그래프에 점,선, 텍스트 장식, 범례 등을 추가로 그리는 함수 이다.예를 들어 다음과 같은 것들이 있다.

points 점을 추가한다.

lines 선을 추가한다

abline 직선을 추가한다

segment 선분을 추가한다

ploygon 닫힌 다각형을 추가한다

text, mtext 텍스트를 추가한다.

legend 범례를 추가한다.

plot(mpg~disp,data=mtcars,pch=21,col="black",bg=mtcars$am+2,cex=1.2,
     main="연비와 배기량",
     xlab="배기량(cu.in)",ylab="연비(mile per gallon)",
     xlim=c(0,500),ylim=c(0,40),family="AppleGothic")
legend("topright",legend=c("automatic","manual"),pch=21,col="black",pt.bg=2:3,
       cex=1.2)
text(100,10,"피타고라스의 정리",family="AppleGothic")
text(100,7,labels=expression(italic(c^2==a^2+b^2)))
polygon(c(200,300,300),c(5,10,5))
polygon(c(290,290,300,300),c(5,6,6,5))
text(240,8.2,"c")
text(260,4,"a")
text(320,7.5,"b")
abline(h=20,col="green")
abline(v=400,col="blue")
out=lm(mpg~disp,data=mtcars)
abline(out,col="red",lwd=2,lty="dotted")
arrows(200,30,300,35,angle=30)
title(sub="subtitle")
mtext(side=1,line=2,"mtext,side=1,line=2")
mtext(side=2,line=2,"mtext,side=2,line=2")
mtext(side=3,line=0.5,"mtext,side=3,line=0.5")

plot of chunk unnamed-chunk-5

그래프의 중첩

방법 1 : 고수준 그래픽함수에서 add=TRUE 옵션을 사용한다.

plot(sin,-pi,pi,ylab="y")
plot(cos,-pi,pi,add=T,lty="dotted",col="red")
legend(0,-0.5,legend=c("sin","cos"),lty=1:2,col=1:2)

plot of chunk unnamed-chunk-6

방법 2 : par(new=TRUE)를 이용한다.

F = function(x,a) {1/(1+exp(-a-x))}
curve(F(x,-1),col=1,xlim=c(-5,5),ylim=c(0,1),ylab="f(x)")
par(new=TRUE)
curve(F(x,1),col=2,xlim=c(-5,5),ylim=c(0,1),ylab="",axes=FALSE,lty=2)
title(main=expression(f(x)==frac(1,1+exp(-a-x))))
legend(2,0.4,legend=c("a=-1","a=1"),lty=1:2,col=1:2)

plot of chunk unnamed-chunk-7

그래프의 저장 : 지정된 크기/형식의 화일로 저장할때

help(Devices)

bmp(),jpeg(),png(),pdf(),tiff(),pictex()등을 이용할수 있다.

png(filename="myplot1.png",width=480,height=480,units="px")
plot(mpg~disp,data=mtcars)
dev.off()

화일의 크기 조절은 units로 하는데 “px”(default),“in”(inches),“cm”,“mm”사용가능

R의 기본 그래프

plot(), boxplot() 등은 이미 다룬 내용이다.

matplot

head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
iS<-iris$Species == "setosa"
iV<-iris$Species == "versicolor"
matplot(c(1,8),c(0,4.5),type="n",ylab="Width",xlab="Height",
         main="Petal and Sepal Dimensions in the Blossoms")
matpoints(iris[iS,c(1,3)],iris[iS,c(2,4)],pch="sS",col=c(2,4))
matpoints(iris[iV,c(1,3)],iris[iV,c(2,4)],pch="vV",col=c(2,4))

plot of chunk unnamed-chunk-10

barplot

x=matrix(c(3,7,8,2),ncol=2)
colnames(x)=1:2
x
##      1 2
## [1,] 3 8
## [2,] 7 2
barplot(x,beside=T)

plot of chunk unnamed-chunk-11

barplot(x,horiz=T)

plot of chunk unnamed-chunk-11

boxplot

boxplot(mpg~cyl,data=mtcars)

plot of chunk unnamed-chunk-12

boxplot(mpg~cyl,data=mtcars,horizontal=TRUE)

plot of chunk unnamed-chunk-12

boxplot(mpg~cyl+am,data=mtcars,col=rep(c("lightblue","lightgreen"),each=3))

plot of chunk unnamed-chunk-12

boxplot(mpg~am+cyl,data=mtcars,col=rep(c("lightblue","lightgreen")))

plot of chunk unnamed-chunk-12

pairs()

pairs(mtcars)

plot of chunk unnamed-chunk-13

round(cor(mtcars),2)
##        mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
## mpg   1.00 -0.85 -0.85 -0.78  0.68 -0.87  0.42  0.66  0.60  0.48 -0.55
## cyl  -0.85  1.00  0.90  0.83 -0.70  0.78 -0.59 -0.81 -0.52 -0.49  0.53
## disp -0.85  0.90  1.00  0.79 -0.71  0.89 -0.43 -0.71 -0.59 -0.56  0.39
## hp   -0.78  0.83  0.79  1.00 -0.45  0.66 -0.71 -0.72 -0.24 -0.13  0.75
## drat  0.68 -0.70 -0.71 -0.45  1.00 -0.71  0.09  0.44  0.71  0.70 -0.09
## wt   -0.87  0.78  0.89  0.66 -0.71  1.00 -0.17 -0.55 -0.69 -0.58  0.43
## qsec  0.42 -0.59 -0.43 -0.71  0.09 -0.17  1.00  0.74 -0.23 -0.21 -0.66
## vs    0.66 -0.81 -0.71 -0.72  0.44 -0.55  0.74  1.00  0.17  0.21 -0.57
## am    0.60 -0.52 -0.59 -0.24  0.71 -0.69 -0.23  0.17  1.00  0.79  0.06
## gear  0.48 -0.49 -0.56 -0.13  0.70 -0.58 -0.21  0.21  0.79  1.00  0.27
## carb -0.55  0.53  0.39  0.75 -0.09  0.43 -0.66 -0.57  0.06  0.27  1.00
library(corrplot)
corrplot(cor(mtcars))

plot of chunk unnamed-chunk-13

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=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)
}
round(cor(iris[,1:4]),2)
##              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
pairs(iris[,1:4],upper.panel=panel.cor)    

plot of chunk unnamed-chunk-13