통계에서 빼놓을 수 없는 기본 개념 중의 하나가 확률입니다.  모집단에서 표본을 추출할 때 랜덤 샘플링, 층화 랜덤 샘플링 등과 같이 확률을 사용합니다.  추정과 검정에서도 확률분포를 사용합니다.  회귀분석, 판별분석 등에서도 변수가 정규분포를 따르고 있는지 검정합니다.  시뮬레이션을 할 때 모집단의 확률분포에 따라 난수를 발생시키기도 합니다.

 

특히, 통계를 좀 공부했던 분이라면 정규분포는 알고 있을 듯 합니다.  하지만, 그 외에 분포들은 들어는 봤어도 모양이 어떻게 생겼는지, 어떤 때 사용하는 것인지 정확히 모르고 있는 경우가 더 많을 듯 합니다.

 

R ggplot2를 활용해서 연속확률분포 곡선을 그려보면 분포별로 모양을 이해하는데 도움이 되겠지요.  그리고 모수에 따라서 모양이 어떻게 바뀌는지도 확인해 볼 수 있겠구요.

 

이번 포스팅에서는 주로 'd'로 시작하는 밀도 함수 (Density Function) 에 대해서 정규분포(norm), t-분포(t), 카이제곱분포(chisq), 지수분포(exp), F분포(f), 감마분포(gamma), 균등분포(unif) 등의 분포에 대해서 ggplot2로 그리는 방법을 소개해보겠습니다. 

 

 

[ 연속확률분포 종류별 / 함수 종류별 ggplot2 그리기 함수 종합표 ]

 

분포 

밀도 함수

d

누적분포 함수

p

분위수 함수 

q

난수 발생 

r

정규분포 

 norm()

 dnorm()

 pnorm()

qnorm()

rnorm() 

 t-분포

 t()

 dt()

 pt()

qt() 

rt() 

카이제곱분포 

 chisq()

 dchisq()

 pchisq()

qchisq() 

rchisq() 

 지수분포

exp() 

 dexp()

 pexp()

qexp() 

rexp() 

 F분포

 f()

 df()

 pf()

qf() 

rf() 

 감마분포

 gamma()

 dgamma()

 pgamma()

qgamma()

rgamma() 

균등분포 

 unif()

 dunif()

 punif()

qunif() 

runif() 

 

 

ggplot2는 별도의 설치 및 호출이 필요한 패키지이므로 아래의 절차를 먼저 실행합니다.

 

> install.packages("ggplot2")
Installing package into ‘C:/Users/user/Documents/R/win-library/3.2’
(as ‘lib’ is unspecified)
trying URL 'http://cran.rstudio.com/bin/windows/contrib/3.2/ggplot2_1.0.1.zip'
Content type 'application/zip' length 2676292 bytes (2.6 MB)
downloaded 2.6 MB

package ‘ggplot2’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
	C:\Users\user\AppData\Local\Temp\RtmpGAPkIo\downloaded_packages
> library(ggplot2) 

 

 

(1) 정규분포 활률밀도곡선 (Normal Distribution Probability Density Curve)

    : stat_function(fun = dnorm)

 

> # 정규분포 : fun = dnorm
> ggplot(data.frame(x=c(-3,3)), aes(x=x)) +
+   stat_function(fun=dnorm, colour="blue", size=1) +
+   ggtitle("Normal Distribution")

 

 

 

 

 

 

(2) 정규분포의 특정 구간에만 색깔 넣기 (colour at specific range of normal distribution)

 

> # 함수 특정 구간에 색깔 넣기
> dnorm_range <- function(x) {
+   y <- dnorm(x) 
+   y[x < -1 | x > 2] <- NA  # 이 범위에는 색깔 없음
+   return(y)
+ }
> 
> ggplot(data.frame(x=c(-3,3)), aes(x=x)) +
+   stat_function(fun=dnorm, colour="blue", size=1) +
+   stat_function(fun=dnorm_range, geom="area", fill="grey", alpha=0.5) + 

+ ggtitle("Normal Distribution of x~N(0,1) with colour from -1 to 2")

 

 

 

 

 

(3) 누적정규분포 (Cummulative Normal Distribution) : stat_function(fun = pnorm)

 

> # 누적정규분포 : fun = pnorm
> ggplot(data.frame(x=c(-3,3)), aes(x=x)) +
+   stat_function(fun=pnorm, colour="black", size=1.5) +
+   ggtitle("Cumulative Normal Distribution of x~N(0,1)")

 

 

 

 

 

 

(4) 정규분포 : 평균과 분산 지정 (Normal Distribution with specific mean and standard deviation) : stat_function(fun = dnorm, args=list(mean=2, sd=1))

 

> # 정규분포: 평균과 분산 지정
> ggplot(data.frame(x = c(-5, 5)), aes(x=x)) +
+   stat_function(fun=dnorm, args=list(mean=2, sd=1), colour="black", size=1.5) +
+   geom_vline(xintercept=2, colour="grey", linetype="dashed", size=1) + # 평균에 세로 직선 추가
+   geom_text(x=0, y=0.3, label="x = N(2, 1)") +
+   ggtitle("Normal Distribution of x~N(2,1)")

 

 

 

 

 

 

(5) t-분포 (t-Distribution) : stat_function(fun = dt)

 

> # t-분포 : fun = dt 
> ggplot(data.frame(x=c(-3,3)), aes(x=x)) +
+   stat_function(fun=dt, args=list(df=2), colour="red", size=2) +
+   ggtitle("t-Distribution of df=2")

 

 

 

 

 

(6) 카이제곱분포 확률밀도곡선 (Chisq Distribution Probability Density Curve)
     : stat_function(fun = dchisq)

 

> # 카이제곱분포 : fun = dchisq
> ggplot(data.frame(x=c(0,10)), aes(x=x)) +
+   stat_function(fun=dchisq, args=list(df=1), colour="black", size=1.2) +
+   geom_text(x=0.6, y=1, label="df=1") +
+   
+   stat_function(fun=dchisq, args=list(df=2), colour="blue", size=1.2) +
+   geom_text(x=0, y=0.55, label="df=2") +
+   
+   stat_function(fun=dchisq, args=list(df=3), colour="red", size=1.2) +
+   geom_text(x=0.5, y=0.05, label="df=3") +
+   
+   ggtitle("Chisq-Distribution")

 

 

 

 

 

(7) 지수분포 (Exponential Distribution) : stat_function(fun = dexp)

 

> # 지수분포 : fun = dexp
> ggplot(data.frame(x=c(0,10)), aes(x=x)) +
+   stat_function(fun=dexp, colour="brown", size=1.5) +
+   ggtitle("Exponential Distribution")

 

 

 

 

 

(8) F 분포 (F Distribution) : stat_function(fun = df)

 

> # F분포 : fun = df
> ggplot(data.frame(x=c(0,5)), aes(x=x)) +
+   stat_function(fun=df, args=list(df1=5, df2=10), colour="purple", size=1) +
+   ggtitle("F Distribution of (df1=5, df2=10)")
 

 

 

 

(9) 감마 분포 (Gamma Distribution) : stat_function(fun = dgamma)

 

> # 감마 분포 : fun = dgamma
> ggplot(data.frame(x=c(0, 400)), aes(x=x)) +
+   stat_function(fun=dgamma, args=list(shape=5, rate=0.05), colour="green") +
+   ggtitle("Gamma Distribution of (shape=5, rate=0.05)")

 

 

 

 

 

 

(10) 균등분포 (Uniform Distribution) : stat_function(fun = dunif)

 

> # 균등분포 : fun = dunif
> ggplot(data.frame(x=c(-2,20)), aes(x=x)) +
+   stat_function(fun=dunif, args=list(min = 0, max = 10), colour="black", size=1) +
+   ggtitle("Uniform Distribution of (min=1, max=10)")

 

 

 

 

 

 

덤으로, 상용로그분포와 사인 함수, 코사인 함수 곡선도 그려보겠습니다.

 

(11) 상용로그분포 (Common Logarithm Distribution) : stat_function(fun = log10)

 

> # 상용로그분포 : fun = log10
> ggplot(data.frame(x=c(0,100)), aes(x=x)) +
+   stat_function(fun=log10, colour="black", size=1.5) +
+   geom_vline(xintercept=10, colour="grey", linetype="dashed", size=1) +
+   geom_vline(xintercept=100, colour="grey", linetype="dashed", size=1) +
+   ggtitle("Common Logarithm Distribution")

 

 

 

 

 

 

(12) 사인 함수 곡선(Sine Function Curve), 코사인 함수 곡선(Cosine Function Curve) :

      stat_function(fun = sin), stat_fuction(fun = cos)

 

> # 사인 함수 : fun = sin, 코사인 함수 : fun = cos
> ggplot(data.frame(x=c(0,6.28)), aes(x=x)) +
+   stat_function(fun=sin, colour="blue", size=1) +
+   geom_text(x=0.2, y=0, label="sine curve") +
+   
+   stat_function(fun=cos, colour="yellow", size=1) + 
+   geom_text(x=0.2, y=1, label="cosine curve") +
+   
+   geom_vline(xintercept=3.14, colour="grey", linetype="dashed", size=1) + # pi값에 세로 직선 추가  
+   geom_vline(xintercept=6.28, colour="grey", linetype="dashed", size=1) + # 2pi값에 세로 직선 추가  
+   ggtitle("Sine(blue curve), Cosine(yellow curve) Function")

 

 

 

 

많은 도움 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^

 

728x90
반응형
Posted by Rfriend
,

x축과 y축으로 나타낸 그래프 혹은 2차원의 지도 위에 특정 연속형 변수의 값에 따라 색깔을 조금씩 다르게 하여 정보를 보여주는 시각화 방법으로 히트맵(Heat map)이 많이 사용됩니다. 

 

R ggplot2 패키지에서는 geom_tile(), geom_raster() 함수를 사용해서 쉽고 편하게 히트맵(Heat map)을 그릴 수 있습니다. 

 

이번 포스팅에서는 히트맵(Heat map)을 그리고, 축의 항목 위치를 바꾸어 보는 것을 예를 들어보이겠습니다.

 

아래 보시는 것은 구글에 히트맵(Heat map) 이라는 키워드로 나온 이미지들인데요, 평소에 알게 모르게 히트맵을 우리가 많이 접하고 있었다는 것을 알 수 있을 것입니다.

 

 

[히트맵 (Heat map) 예시 ]

 

* 이미지 출처 : 구글(www.google.co.kr)

 

 

MASS 패키지에 내장되어 있는 Cars93 데이터 프레임이며, 차종(Type), 실린더(Cylinders) 별 고속도로연비(MPG.highway) 를 사용하여 히트맵(Heat map)을 그려보겠습니다.

 

 

 
> library(MASS)
> str(Cars93)
'data.frame':	93 obs. of  27 variables:
 $ Manufacturer      : Factor w/ 32 levels "Acura","Audi",..: 1 1 2 2 3 4 4 4 4 5 ...
 $ Model             : Factor w/ 93 levels "100","190E","240",..: 49 56 9 1 6 24 54 74 73 35 ...
 $ Type              : Factor w/ 6 levels "Compact","Large",..: 4 3 1 3 3 3 2 2 ...
 $ Min.Price         : num  12.9 29.2 25.9 30.8 23.7 14.2 19.9 22.6 26.3 33 ...
 $ Price             : num  15.9 33.9 29.1 37.7 30 15.7 20.8 23.7 26.3 34.7 ...
 $ Max.Price         : num  18.8 38.7 32.3 44.6 36.2 17.3 21.7 24.9 26.3 36.3 ...
 $ MPG.city          : int  25 18 20 19 22 22 19 16 19 16 ...
 $ MPG.highway       : int  31 25 26 26 30 31 28 25 27 25 ...
 $ AirBags           : Factor w/ 3 levels "Driver & Passenger",..: 3 1 2 1 2 2 2 2 2 2 ...
 $ DriveTrain        : Factor w/ 3 levels "4WD","Front",..: 2 2 2 2 3 2 2 3 2 2 ...
 $ Cylinders         : Factor w/ 6 levels "3","4","5","6",..: 2 4 4 4 2 2 4 4 ...
 $ EngineSize        : num  1.8 3.2 2.8 2.8 3.5 2.2 3.8 5.7 3.8 4.9 ...
 $ Horsepower        : int  140 200 172 172 208 110 170 180 170 200 ...
 $ RPM               : int  6300 5500 5500 5500 5700 5200 4800 4000 4800 4100 ...
 $ Rev.per.mile      : int  2890 2335 2280 2535 2545 2565 1570 1320 1690 1510 ...
 $ Man.trans.avail   : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 1 1 1 1 ...
 $ Fuel.tank.capacity: num  13.2 18 16.9 21.1 21.1 16.4 18 23 18.8 18 ...
 $ Passengers        : int  5 5 5 6 4 6 6 6 5 6 ...
 $ Length            : int  177 195 180 193 186 189 200 216 198 206 ...
 $ Wheelbase         : int  102 115 102 106 109 105 111 116 108 114 ...
 $ Width             : int  68 71 67 70 69 69 74 78 73 73 ...
 $ Turn.circle       : int  37 38 37 37 39 41 42 45 41 43 ...
 $ Rear.seat.room    : num  26.5 30 28 31 27 28 30.5 30.5 26.5 35 ...
 $ Luggage.room      : int  11 15 14 17 13 16 17 21 14 18 ...
 $ Weight            : int  2705 3560 3375 3405 3640 2880 3470 4105 3495 3620 ...
 $ Origin            : Factor w/ 2 levels "USA","non-USA": 2 2 2 2 2 1 1 1 1 1 ...
 $ Make              : Factor w/ 93 levels "Acura Integra",..: 1 2 4 3 5 6 7 9 8 10 ...

 

 

 

 

ggplot2는 별도의 설치 및 호출이 필요하므로 아래의 절차를 먼저 거치고 히트맵을 그려보겠습니다.

 

 
> install.packages("ggplot2")
> library(ggplot2)
 

 

 

 

x축에 차종(Type), y축에 실린더개수(Cylinders)별로 고속도로연비(MPG.highway)에 따라서 색을 달리하여 히트맵을 geom_tile() 함수를 사용해 그려보겠습니다.

 

 
> # Type, Cylinders 별 MPG.highway Heatmap : geom_tile()
> a1 <- ggplot(Cars93, aes(x=Type, y=Cylinders, fill=MPG.highway)) +
+   geom_tile()
> 
> a1

 

 

 

 

 

위의 히트맵을 보면 x축에 차종(Type)이 차의 크기 순서가 아니라 알파벳 순서로 되어 있다보니 색깔이 경향성이 없이 무작위하게 채워져있어 보입니다.  x축을 차의 크기를 감안한 순서대로, 즉, "Small", "Compact", "Midsize", "Sporty", "Large", "Van" 의 순서대로 scale_x_discrete(limits=...) 를 사용해 바꾸어보겠습니다.

 

 
> # x축 순서 바꾸기 : scale_x_discrete(limits=...)
> a2 <- a1 + 
+   scale_x_discrete(limits=c("Small", "Compact", "Midsize", "Sporty", "Large", "Van"))
> 
> a2

 

 

 

 

 

위의 히트맵을 보니 크기가 작을 수록, 실린더 개수가 작을 수록 고속도로 연비가 높으며, 그 반대는 고속도로 연비가 낮아짐을 한눈에 단박에 파악할 수 있게 되었습니다.

 

 

이번에는 geom_raster() 함수를 사용해 히트맵을 그려보겠습니다.  결과적으로 geom_tile()과 차이가 거의 없다는 것을 알 수 있습니다.

 

 
> # Type, Cylinders 별 MPG.highway Heatmap : geom_raster()
> ggplot(Cars93, aes(x=Type, y=Cylinders, fill=MPG.highway)) +
+   geom_raster() + 
+   scale_x_discrete(limits=c("Small", "Compact", "Midsize", "Sporty", "Large", "Van"))

 

 

 

 

 


연속형 숫자형 값을 가지는 히트맵의 색상을 scale_fill_gradient(low = "colour 1", high = "colour 2") 옵션을 사용해서 다르게 설정해보도록 하겠습니다. (kusscd 님, 댓글로 방법 공유해주셔서 감사합니다 ^^)



> ggplot(Cars93, aes(x=Type, y=Cylinders, fill=MPG.highway)) + # filling with numeric value

+   geom_tile() +

+   scale_x_discrete(limits = c("Small", "Compact", "Midsize", "Sporty", "Large", "Van")) +

+   scale_fill_gradient(low = "yellow", high = "red") +

+   ggtitle("Heatmap of MPG.highway by Type & Cylinders")


 






다음으로, 범주형 자료로 히트맵의 색상을 채우는 경우에 scale_fill_manual(values = c("colour 1", "colour 2", ...) 을 옵션을 사용해서 색상을 사용자가 직접 지정해주는 방법을 2개 범주를 가지는 간단한 예시를 들어서 설명하겠습니다. 



> my.df <- data.frame(XCoord = c(1, 1, 2, 3, 3, 4, 4, 5, 5, 5), 

+                     YCoord = c(1, 4, 3, 1, 3, 1, 5, 2, 3, 5), 

+                     Seg = c("A", "A", "A", "A", "B", "A", "B", "B", "B", "B"))

> ggplot(my.df, aes(x=XCoord, y=YCoord, fill=Seg)) + # filling with categorical value

+   geom_tile(colour="white") +

+   scale_fill_manual(values = c("blue", "red")) +

+   ggtitle("Heatmap with 2 categories with scale_fill_manual()")




 



 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^

 

728x90
반응형
Posted by Rfriend
,

범주형 변수의 그룹(요인)을 x 축으로 한 그래프를 그리면 디폴트는 알파벳 순서대로 그룹이 제시가 됩니다.  만약 순서형 요인(ordered factor)으로 범주형 변수를 만들었다면 그 순서에 따라서 그래프가 그려질 겁니다. 

 

그런데 분석가가 범주형 변수의 그룹의 순서를 ggplot2가 디폴트로 그려준 것과는 달리 바꾸고 싶어할 수 있습니다. 

 

이때 scale_x_discrete(limits=c(...) 함수를 사용해서 그룹의 순서를 바꿀 수 있습니다.

 

 

아래의 예제에 사용할 데이터는 iris 데이터프레임의 Petal.Length 와 Species 두 개의 변수입니다. Species 가 요인(Factor)형 변수이며, "setosa", "versicolor", "virginica" 의 3개 Levels 로 구성이 되어있습니다.

 

 
> str(iris)
'data.frame':	150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

 

 

ggplot2 패키지를 사용해서 Species를 x축으로 Petal.Length 를 y축으로 해서 Box plot을 그려보겠습니다.  이를 위해서 먼저 데이터셋을 ggplot2에서 사용할 수 있는 형태로 변환이 필요합니다.  가로로 옆으로 늘어서있는 원래의 iris 데이터셋을 reshape 패키지를 사용해서 melt() 함수를 적용하여 세로로 길게 세워보겠습니다. (☞ reshape 패키지 melt(), cast() 함수 사용법 둘러보기)

 

 
> # dataset preparation
> library(reshape)
> iris_melt_petal.length <- melt(data=iris, 
+                   id.vars = c("Species"), 
+                   measure.vars = c("Petal.Length"))
> 
> iris_melt_petal.length
       Species     variable value
1       setosa Petal.Length   1.4
2       setosa Petal.Length   1.4
3       setosa Petal.Length   1.3
4       setosa Petal.Length   1.5
5       setosa Petal.Length   1.4
6       setosa Petal.Length   1.7
7       setosa Petal.Length   1.4
8       setosa Petal.Length   1.5
9       setosa Petal.Length   1.4
10      setosa Petal.Length   1.5
11      setosa Petal.Length   1.5
12      setosa Petal.Length   1.6
13      setosa Petal.Length   1.4
14      setosa Petal.Length   1.1
15      setosa Petal.Length   1.2
16      setosa Petal.Length   1.5
17      setosa Petal.Length   1.3
18      setosa Petal.Length   1.4
19      setosa Petal.Length   1.7
20      setosa Petal.Length   1.5
21      setosa Petal.Length   1.7
22      setosa Petal.Length   1.5
23      setosa Petal.Length   1.0
24      setosa Petal.Length   1.7
25      setosa Petal.Length   1.9
26      setosa Petal.Length   1.6
27      setosa Petal.Length   1.6
28      setosa Petal.Length   1.5
29      setosa Petal.Length   1.4
30      setosa Petal.Length   1.6
31      setosa Petal.Length   1.6
32      setosa Petal.Length   1.5
33      setosa Petal.Length   1.5
34      setosa Petal.Length   1.4
35      setosa Petal.Length   1.5
36      setosa Petal.Length   1.2
37      setosa Petal.Length   1.3
38      setosa Petal.Length   1.4
39      setosa Petal.Length   1.3
40      setosa Petal.Length   1.5
41      setosa Petal.Length   1.3
42      setosa Petal.Length   1.3
43      setosa Petal.Length   1.3
44      setosa Petal.Length   1.6
45      setosa Petal.Length   1.9
46      setosa Petal.Length   1.4
47      setosa Petal.Length   1.6
48      setosa Petal.Length   1.4
49      setosa Petal.Length   1.5
50      setosa Petal.Length   1.4
51  versicolor Petal.Length   4.7
52  versicolor Petal.Length   4.5
53  versicolor Petal.Length   4.9
54  versicolor Petal.Length   4.0
55  versicolor Petal.Length   4.6
56  versicolor Petal.Length   4.5
57  versicolor Petal.Length   4.7
58  versicolor Petal.Length   3.3
59  versicolor Petal.Length   4.6
60  versicolor Petal.Length   3.9
61  versicolor Petal.Length   3.5
62  versicolor Petal.Length   4.2
63  versicolor Petal.Length   4.0
64  versicolor Petal.Length   4.7
65  versicolor Petal.Length   3.6
66  versicolor Petal.Length   4.4
67  versicolor Petal.Length   4.5
68  versicolor Petal.Length   4.1
69  versicolor Petal.Length   4.5
70  versicolor Petal.Length   3.9
71  versicolor Petal.Length   4.8
72  versicolor Petal.Length   4.0
73  versicolor Petal.Length   4.9
74  versicolor Petal.Length   4.7
75  versicolor Petal.Length   4.3
76  versicolor Petal.Length   4.4
77  versicolor Petal.Length   4.8
78  versicolor Petal.Length   5.0
79  versicolor Petal.Length   4.5
80  versicolor Petal.Length   3.5
81  versicolor Petal.Length   3.8
82  versicolor Petal.Length   3.7
83  versicolor Petal.Length   3.9
84  versicolor Petal.Length   5.1
85  versicolor Petal.Length   4.5
86  versicolor Petal.Length   4.5
87  versicolor Petal.Length   4.7
88  versicolor Petal.Length   4.4
89  versicolor Petal.Length   4.1
90  versicolor Petal.Length   4.0
91  versicolor Petal.Length   4.4
92  versicolor Petal.Length   4.6
93  versicolor Petal.Length   4.0
94  versicolor Petal.Length   3.3
95  versicolor Petal.Length   4.2
96  versicolor Petal.Length   4.2
97  versicolor Petal.Length   4.2
98  versicolor Petal.Length   4.3
99  versicolor Petal.Length   3.0
100 versicolor Petal.Length   4.1
101  virginica Petal.Length   6.0
102  virginica Petal.Length   5.1
103  virginica Petal.Length   5.9
104  virginica Petal.Length   5.6
105  virginica Petal.Length   5.8
106  virginica Petal.Length   6.6
107  virginica Petal.Length   4.5
108  virginica Petal.Length   6.3
109  virginica Petal.Length   5.8
110  virginica Petal.Length   6.1
111  virginica Petal.Length   5.1
112  virginica Petal.Length   5.3
113  virginica Petal.Length   5.5
114  virginica Petal.Length   5.0
115  virginica Petal.Length   5.1
116  virginica Petal.Length   5.3
117  virginica Petal.Length   5.5
118  virginica Petal.Length   6.7
119  virginica Petal.Length   6.9
120  virginica Petal.Length   5.0
121  virginica Petal.Length   5.7
122  virginica Petal.Length   4.9
123  virginica Petal.Length   6.7
124  virginica Petal.Length   4.9
125  virginica Petal.Length   5.7
126  virginica Petal.Length   6.0
127  virginica Petal.Length   4.8
128  virginica Petal.Length   4.9
129  virginica Petal.Length   5.6
130  virginica Petal.Length   5.8
131  virginica Petal.Length   6.1
132  virginica Petal.Length   6.4
133  virginica Petal.Length   5.6
134  virginica Petal.Length   5.1
135  virginica Petal.Length   5.6
136  virginica Petal.Length   6.1
137  virginica Petal.Length   5.6
138  virginica Petal.Length   5.5
139  virginica Petal.Length   4.8
140  virginica Petal.Length   5.4
141  virginica Petal.Length   5.6
142  virginica Petal.Length   5.1
143  virginica Petal.Length   5.1
144  virginica Petal.Length   5.9
145  virginica Petal.Length   5.7
146  virginica Petal.Length   5.2
147  virginica Petal.Length   5.0
148  virginica Petal.Length   5.2
149  virginica Petal.Length   5.4
150  virginica Petal.Length   5.1

 

 

 

 

데이터셋 준비가 되었으므로, 디폴트 설정으로 해서 x축에 Species, y축에 Petal.Length로 Box plot 을 그려보겠습니다.  ggplot2는 별도의 설치 및 호출이 필요하므로 install.packages("ggplot2")와 library(ggplot2)를 먼저 실행 후 그래프를 그립니다.  x축의 요인(factor)의 순서가 위에서 살펴본것처럼 "setosa", "versicolor", "virginica"  의 알파벳 순서로 되어있습니다.

 

 

> install.packages("ggplot2")
> library(ggplot2)
> 

> # Boxplot of Petal.Length > f1 <- ggplot(iris_melt_petal.length, aes(x=Species, y=value)) + + geom_boxplot() + + ggtitle(("Boxplot of Petal.Length")) > f1

 

 

 

 

 

 

 

이것을 분석가가 필요에 따라서 순서를 "virginica", "versicolor", "setosa" 처럼 바꾸고 싶다고 해봅시다.  이때 사용하는 것이 scale_x_discrete(limit=...) 함수입니다.

 

 
> f2 <- f1 + 
+   scale_x_discrete(limits=c("virginica", "versicolor", "setosa")) + 
+   ggtitle("Changed Order of x axis by scale_x_discrete(limit=...)")
> 
> f2

 

 

 

 

 

첫번째에 디폴트로 그린 박스그림과 두번째에 범주형 축 그룹 순서를 바꾼 그래프의 차이를 아시겠지요?  많은 도움 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^

 

728x90
반응형
Posted by Rfriend
,

이전 포스팅에서 하나의 그래프에 텍스트, 선, 화살표, 음영있는 사각형 등으로 부연 설명을 추가하기 위해 annotate() 함수로 주석을 추가하는 방법을 소개하였습니다. 

 

이번에는 facet_grid() 로 특정 범주형 변수에 의해 요인(factor)별로 면 분할된 그래프에 각각 주석을 넣는 넣기 위해 geom_text() 함수를 사용하는 방법에 대해 알아보겠습니다.

 

 

예제로 사용할 데이터는 iris 데이터프레임 내 Petal.Width, Petal.Length, Species 의 3개 변수를 사용하겠습니다.

 

 
> str(iris)
'data.frame':	150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
 

 

 

 

ggplot2는 별도의 설치 및 호출이 필요한 패키지이므로 아래의 절차를 먼저 따르기 바랍니다.

 

 
> install.packages("ggplot2")
Installing package into ‘C:/Users/user/Documents/R/win-library/3.2’
(as ‘lib’ is unspecified)
trying URL 'http://cran.rstudio.com/bin/windows/contrib/3.2/ggplot2_1.0.1.zip'
Content type 'application/zip' length 2676992 bytes (2.6 MB)
downloaded 2.6 MB

package ‘ggplot2’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
	C:\Users\user\AppData\Local\Temp\Rtmp0CW98B\downloaded_packages
> library(ggplot2)
 

 

 

 

먼저, 지난번 포스팅에서 소개드렸던, 하나의 화면에 품종별로 색깔을 구분해서 그리고, annotate() 함수를 사용해서 텍스트 주석(text annotation) 하는 방법을 아래에 복습해 보겠습니다.

 

 

> # 하나의 화면에 품종별로 색깔 구분해서 그리기 : aes(fill=categorical var)
> a1 <- ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Species)) + 
+   geom_point(colour="grey", shape=21, size=6) +
+   scale_fill_brewer(palette="Reds") + 
+   annotate("text", x=0.25, y=2.4, label="Setosa", size=7) + # text annotation
+   annotate("text", x=1.3, y=3.3, label="Versicolor", size=7) + 
+   annotate("text", x=1.7, y=6.8, label="Virginica", size=7)
> 
> a1

 

 

 

 

 

 


 

 

이걸 품종(Species)을 기준으로 면 분할 (facet_grid(.~Species) ) 하면 아래와 같습니다.  이번 포스팅에서는 아래 처럼 면 분할 된 상태의 그래프에 주석 추가하는 방법입니다.

 

 
> # 품종별로 면 분할하여 색깔 구분없이 그리기 : facet_grid(.~categorical var)
> g1 <- ggplot(iris, aes(x=Petal.Width, y=Petal.Length)) + 
+   geom_point(colour="blue", shape=19, size=4) +
+   facet_grid(.~Species)
> 
> g1

 

 

 

 

 

 

범주형 변수의 요인(factor)별로 면 분할된 상태의 그래프에 텍스트 주석을 넣으려고 아래와 같이 하면 라벨 길이가 다르다면서 에러가 납니다.

 

 
> # 텍스트 라벨 넣으려면 에러 발생 
> # Error: Incompatible lengths for set aesthetics: label
> g1 + 
+   annotate("text", x=1, y=7, label=c("Setosa", "Versicolor", "Virginica"))
Error: Incompatible lengths for set aesthetics: label

 

 

 

 

범주형 변수의 요인(factor)별로 면 분할된 상태의 그래프에 텍스트 주석을 넣으려고 하려면 annotate() 함수로는 안되구요, 라벨을 넣으려는 내용을 데이터프레임으로 미리 만들어놓고 geom_text()로 라벨을 집어넣어야 합니다. 아래 예제는 Species 이름을 각 각 텍스트로 넣어보는 예입니다.

 

 

> # 분할 면마다 각각 텍스트 주석 넣기 : geom_text()

> # dataframe of label
> iris_species_labels <- data.frame(Species = c("setosa", "versicolor", "virginica"), 
+                        label = c("Species=Setosa", "Species=Versicolor", "Species=Virginica"))
> 
> g2 <- g1 + 
+   geom_text(x=1, y=6.5, aes(label=label), data=iris_species_labels)
>   
> g2

 

 

 

 

 

 

 


 

 

다음으로 각 품종(Species)별로 x축 Petal.Width와 y축 Petal.Length 평균을 구해서 중심 좌표 (centroid)를 텍스트로 주석을 추가해보겠습니다.

 

먼저, sqldf 패키지를 새로 설치해서 x축 Petal.Width와 y축 Petal.Length 평균을 구해보겠습니다.

 

 

> install.packages("sqldf") > library(sqldf) > > mean_iris <- sqldf('select "Species", + avg("Petal.Width") as "mean_Petal.Width", + avg("Petal.Length") as "mean_Petal.Length" + from iris + group by Species + order by Species + ') > > mean_iris Species mean_Petal.Width mean_Petal.Length 1 setosa 0.246 1.462 2 versicolor 1.326 4.260 3 virginica 2.026 5.552 

 

> label_mean_iris <- transform(mean_iris, 
+                              centroid=paste(c("centroid("), 
+                                             round(mean_Petal.Width, 2), 
+                                             c(", "), 
+                                             round(mean_Petal.Length, 2), 
+                                             c(")"), 
+                                             sep=""))
> 
> label_mean_iris
     Species mean_Petal.Width mean_Petal.Length             centroid
1     setosa            0.246             1.462 centroid(0.25, 1.46)
2 versicolor            1.326             4.260 centroid(1.33, 4.26)
3  virginica            2.026             5.552 centroid(2.03, 5.55)
 

 

 

 

다음으로 centroid 정보를 그래프에 분할된 면에 따라 각각 추가해보겠습니다.

 

 
> # x, y 평균 좌표 추가 : geom_text()
> g3 <- g2 +
+   geom_text(x=1, y=6, aes(label=centroid), data=label_mean_iris)
> 
> g3

 

 

 

 

많은 도움이 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^

 

 

728x90
반응형
Posted by Rfriend
,

그동안 R로 다양한 그래프를 그리는 방법을 알아보았습니다.  R로 그래프를 그렸다면, 보는 이의 가독성, 해석의 용이성을 높여주기 위해서 그래프 위에 텍스트, 가로선/세로선/대각선, 화살표, 음영 사각형, 제목 등과 같이 추가로 정보를 제공하거나 강조를 하고 싶은 부분에 주석을 달고 싶을 때가 있습니다.

 

 

- 텍스트 : annotate("text")

 

- 가로선/세로선/대각선 : geom_vline(), geom_hline(), geom_abline()

 

- 화살표 : annotate("segment", arrow=arrow()) , with grid package


- 음영 사각형 : annotate("rect")


- 제목 : ggtitle()

 

 

매번의 R 그래프/시각화 포스팅마다 주석 다는 방법을 간간이 곁들여서 소개해드리기는 했는데요, 이번 포스팅에서는 주석 다는 방법에 대해서 포괄적이고 종합적으로 정리를 해서 바로 찾아보기 편하도록 정리를 해보았습니다.

 

 

예제로 사용할 데이터는 Base Package에 내장되어 있는 iris 데이터 프레임의 Petal.Width, Petal.Length, Species 의 세개 변수를 사용하겠습니다. (iris 데이터셋은 데이터 마이닝 실습에 아주 많이 사용되는 데이터셋으로서, iris 꽃 품종 중 setosa 50개, versicolor 50개, virginica 50개를 꽃잎의 넓이와 길이를 측정해놓은 데이터셋입니다)

 

 

 

> str(iris)
'data.frame':	150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ... 

 

 

ggplot2는 별도의 설치 및 호출이 필요한 패키지이므로 아래의 절차를 먼저 실행하시기 바랍니다.

 

> install.packages("ggplot2")
Installing package into ‘C:/Users/user/Documents/R/win-library/3.2’
(as ‘lib’ is unspecified)
trying URL 'http://cran.rstudio.com/bin/windows/contrib/3.2/ggplot2_1.0.1.zip'
Content type 'application/zip' length 2676992 bytes (2.6 MB)
downloaded 2.6 MB

package ‘ggplot2’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
	C:\Users\user\AppData\Local\Temp\RtmpEfAwCj\downloaded_packages
> library(ggplot2) 

 

(1) iris의 Petal.Width를 x축으로, Petal.Length를 y축으로 하고, 품종(Species)에 따라서 색깔을 달리해서 산포도(scatter plot)을 그려보겠습니다.

 

> # scatter plot of iris dataset
> a1 <- ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Species)) + 
+   geom_point(colour="grey", shape=21, size=6) +
+   scale_fill_brewer(palette="Reds")
> 
> a1
 

 

 

 

 

(2) 텍스트(text) 추가 : annotate("text")

 

> # 텍스트(text) 추가 : annotate("text")
> 
> a2 <- a1 + 
+   annotate("text", x=0.25, y=2.4, label="Setosa", size=7) + # text annotation
+   annotate("text", x=1.3, y=3.3, label="Versicolor", size=7) + 
+   annotate("text", x=1.7, y=6.8, label="Virginica", size=7)
> 
> a2

 

 

 

 

 

 

(3) 선(line) 추가 : geom_vline(), geom_hline(), geom_abline()

 

> # 선(line) 추가 : geom_vline(), geom_hline(), geom_abline()
> 
> a3 <- a2 + 
+   geom_hline(yintercept=2.6, colour="grey", lty="dashed", size=1) + # horizontal line
+   geom_hline(yintercept=4.9, colour="grey", lty="dashed", size=1) + 
+ 
+   geom_vline(xintercept=0.8, colour="grey", lty="dashed", size=1) + # vertical line
+   geom_vline(xintercept=1.75, colour="grey", lty="dashed", size=1) + 
+   
+   geom_abline(intercept=8, slope=-2.1, colour="red", lty="dotted", size=1.5) # abline
>   
> a3

 

 

 

 

 

(4) 화살표(arrow) 추가 : annotate("segment")

 

단, grid 패키지를 호출해서 사용해야 합니다.

 

> # 화살표(arrow) 추가 : annotate("segment")
> library(grid) # grid 패키지 호출
> 
> a4 <- a3 + 
+   annotate("segment", x=2, xend=2.1, y=2, yend=3.5, size=1.5, colour="red", arrow=arrow())
> 
> a4
> 
> 
> # 텍스트 추가 : annotate("text")
> a5 <- a4 + 
+   annotate("text", x=2, y=1.8, size=6, colour="red", label="y=8 - 2.1x")
> 
> a5

 

 

 

 

 

 

 

(5) 음영 사각형(shadowed box) 추가 : annotate("rect")

 

> # 음영 사각형(shadowed box) 추가 : annotate("rect")
> a6 <- a5 + 
+   annotate("rect", xmin=0, xmax=0.8, ymin=0, ymax=2.6, alpha=0.1, fill="red") + 
+   annotate("rect", xmin=0.8, xmax=1.75, ymin=2.6, ymax=4.9, alpha=0.2, fill="red") + 
+   annotate("rect", xmin=1.3, xmax=2.7, ymin=4.3, ymax=7.2, alpha=0.3, fill="red")
> 
> a6

 

 

 

 

 

(6) 제목(title) 추가 : ggtitle()

 

> # 제목 추가 : ggtitle()
> 
> a7 <- a6 + 
+   ggtitle("Annotation of Text, Line, Arrow, Shadowed Box, Title")
> 
> a7

 

 

 

 

많은 도움 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^

 

728x90
반응형
Posted by Rfriend
,

이번 포스팅에서는 R ggplot2에서 그래프 색깔 설정 (colour setting), 조절하는 방법에 대해서 알아보겠습니다.  이전의 각 그래프 종류별로 소개한 내용에도 색깔 지정에 대한 내용이 조금씩 포함되어 있기는 합니다만, 이번 포스팅에서는 색깔 설정에 대한 경우의 수를 종합적으로 포괄해서 정리를 해보았습니다.

 

그래프에서 색깔을 특정 변수의 변화와 align하게 되면 x축과 y축의 2차원에 색깔이라는 차원을 추가함으로써 3차원의 정보를 제공할 수 있습니다.  회사 업무 보고서에 엑셀로 그린 그래프를 많이 사용하고는 하는데요, x축과 y축의 2차원을 넘어서는, 특정 조건에 따라서 색깔이나 모양을 달리해야 하는 경우라면 엑셀로 그래프를 그리는 것이 거의 불가능하게 됩니다.  이때 R이 데이터 전처리/변환부터 해서 인쇄용으로 바로 사용해도 좋을 만큼의 고품질의 그래프를 그리는데 아주 특출난 역할을 할 수 있습니다.  R 그래프에서 색깔을 자유자재로 사용할 수 있다면 미적으로도 보기에 좋겠지요?!

 

 

이번 예제에서 사용할 데이터는 MASS 패키지에 내장되어 있는 Cars93 데이터 프레임의 차 무게(Weight)와 고속도로연비(MPG.highway), 차 가(Price), 실린더 개수(Cylinders)의 4개 변수를 사용하겠습니다.

 

> library(MASS)
> str(Cars93)
'data.frame':	93 obs. of  27 variables:
 $ Manufacturer      : Factor w/ 32 levels "Acura","Audi",..: 1 1 2 2 3 4 4 4 4 5 ...
 $ Model             : Factor w/ 93 levels "100","190E","240",..: 49 56 9 1 6 24 54 74 73 35 ...
 $ Type              : Factor w/ 6 levels "Compact","Large",..: 4 3 1 3 3 3 2 2 3 2 ...
 $ Min.Price         : num  12.9 29.2 25.9 30.8 23.7 14.2 19.9 22.6 26.3 33 ...
 $ Price             : num  15.9 33.9 29.1 37.7 30 15.7 20.8 23.7 26.3 34.7 ...
 $ Max.Price         : num  18.8 38.7 32.3 44.6 36.2 17.3 21.7 24.9 26.3 36.3 ...
 $ MPG.city          : int  25 18 20 19 22 22 19 16 19 16 ...
 $ MPG.highway       : int  31 25 26 26 30 31 28 25 27 25 ...
 $ AirBags           : Factor w/ 3 levels "Driver & Passenger",..: 3 1 2 1 2 2 2 2 2 2 ...
 $ DriveTrain        : Factor w/ 3 levels "4WD","Front",..: 2 2 2 2 3 2 2 3 2 2 ...
 $ Cylinders         : Factor w/ 6 levels "3","4","5","6",..: 2 4 4 4 2 2 4 4 4 5 ...
 $ EngineSize        : num  1.8 3.2 2.8 2.8 3.5 2.2 3.8 5.7 3.8 4.9 ...
 $ Horsepower        : int  140 200 172 172 208 110 170 180 170 200 ...
 $ RPM               : int  6300 5500 5500 5500 5700 5200 4800 4000 4800 4100 ...
 $ Rev.per.mile      : int  2890 2335 2280 2535 2545 2565 1570 1320 1690 1510 ...
 $ Man.trans.avail   : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 1 1 1 1 ...
 $ Fuel.tank.capacity: num  13.2 18 16.9 21.1 21.1 16.4 18 23 18.8 18 ...
 $ Passengers        : int  5 5 5 6 4 6 6 6 5 6 ...
 $ Length            : int  177 195 180 193 186 189 200 216 198 206 ...
 $ Wheelbase         : int  102 115 102 106 109 105 111 116 108 114 ...
 $ Width             : int  68 71 67 70 69 69 74 78 73 73 ...
 $ Turn.circle       : int  37 38 37 37 39 41 42 45 41 43 ...
 $ Rear.seat.room    : num  26.5 30 28 31 27 28 30.5 30.5 26.5 35 ...
 $ Luggage.room      : int  11 15 14 17 13 16 17 21 14 18 ...
 $ Weight            : int  2705 3560 3375 3405 3640 2880 3470 4105 3495 3620 ...
 $ Origin            : Factor w/ 2 levels "USA","non-USA": 2 2 2 2 2 1 1 1 1 1 ...
 $ Make              : Factor w/ 93 levels "Acura Integra",..: 1 2 4 3 5 6 7 9 8 10 ... 

 

ggplot2 패키지는 별도의 설치 및 호출이 필요하므로 아래의 절차를 먼저 시행합니다.

 

> install.packages("ggplot2") # 설치

> library(ggplot2)  

 

 

색상 변화를 잘 살펴볼 수 있도록 속이 빈 동그라미 모양인 shape=21 번의 도형을 사용해서 size=6 으로 큼지막하게 키워서 예를 들어보겠습니다. 

 

 

(1) 색깔 설정을 별도로 하지 않은 경우 디폴트 테두리 검정색 (default colour)

 

> # default colour
> ggplot(Cars93, aes(x=Weight, y=MPG.highway)) +
+   geom_point(shape=21, size=6)

 

 

 

 

 

(2) 테두리 선 색깔 지정 (colour : line colour setting)

 

> # 테두리 선 색깔 지정 (colour : line colour setting)
> ggplot(Cars93, aes(x=Weight, y=MPG.highway)) +
+   geom_point(shape=21, size=6, colour="blue")

 

 

 

 

 

 

(3) 도형의 속 채우기 색깔 지정 (fill : innner colour fill-up)

 

> # 도형의 속 채우기 색깔 (fill : inner colour fill-up)
> ggplot(Cars93, aes(x=Weight, y=MPG.highway)) +
+   geom_point(shape=21, size=6, fill="blue")

 

 

 

 

 

 

(4) 연속형 변수의 숫자에 따른 색깔 조절 : aes(fill=continuous variable)

 

> # 연속형 변수의 숫자에 따른 색깔 조절
> # (fill : colour change aligned with continuous numeric variable)
> ggplot(Cars93, aes(x=Weight, y=MPG.highway, fill=Price)) +
+   geom_point(colour="grey", shape=21, size=6)

 

 

 

 

 

 

(5) 범주형 변수의 범주/요인(factor)에 따른 색깔 조절 : aes(fill=categorical variable)

 

> # 범주형 변수의 범주/요인(factor) 따른 색깔 조절 
> # (fill : colour change aligned with categorical variable)
> ggplot(Cars93, aes(x=Weight, y=MPG.highway, fill=Cylinders)) +
+   geom_point(colour="grey", shape=21, size=6)

 

 

 

 

 

###  아래의 palette 설정은 범주형 데이터 (categorical data)에만 해당됩니다.  

 

(6) Palette = Oranges 색 설정 (pallet colour setting) : scale_fill_brewer()

 

> # Palette = Oranges 색 설정 (palette colour setting) : scale_fill_brewer()
> ggplot(Cars93, aes(x=Weight, y=MPG.highway, fill=Cylinders)) +
+   geom_point(colour="grey", shape=21, size=6) +
+   scale_fill_brewer(palette="Oranges") # Oranges

 

 

 

 

 

 

(7) Palette = Reds 색 설정 (pallet colour setting) : scale_fill_brewer()

 

> # Palette = Reds 색 설정 (palette colour setting) : scale_fill_brewer()
> ggplot(Cars93, aes(x=Weight, y=MPG.highway, fill=Cylinders)) +
+   geom_point(colour="grey", shape=21, size=6) +
+   scale_fill_brewer(palette="Reds") # Reds

 

 

 

 

 

(8) Palette = Blues 색 설정 (pallet colour setting) : scale_fill_brewer()

 

> # Palette = Blues 색 설정 (palette colour setting) : scale_fill_brewer()
> ggplot(Cars93, aes(x=Weight, y=MPG.highway, fill=Cylinders)) +
+   geom_point(colour="grey", shape=21, size=6) +
+   scale_fill_brewer(palette="Blues") # Blues

 

 

 

 

많은 도움 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^

 

 

728x90
반응형
Posted by Rfriend
,

ggplot2 그래프를 그렸을 때 x축이나 y축의 디폴트 값을 사용해도 무리가 없는 경우가 많기는 합니다만, 

 

분석가가 x축이나 y축을 좀더 사용하는 목적에 맞게 설정을 조정하고 싶을 때가 있습니다. 

 

이때 사용할 수 있는 ggplot2의 함수 3가지를 알아보도록 하겠습니다. 

 

(1) 1:1 의 비율로 x축과 y축 설정

 : coord_fixed()

 

(2) 일정한 간격으로 x축, y축 설정

 : scale_x_continuous(breaks=seq())

 

(3) 분석가 마음대로 x축, y축 설정

 : scale_x_continuous(breaks=c())

 

 

예제로 사용할 데이터는 MASS 패키지에 내장되어 있는 Cars93 데이터 프레임의 도시연비(MPG.city), 고속도로연비(MPG.highway)가 되겠습니다.  scale이 연비로서 서로 같은 변수를 선택하였으며, 산점도를 그려보면서 x축, y축 설정을 바꿔보도록 하겠습니다.

 

> library(MASS)
> str(Cars93)
'data.frame':	93 obs. of  27 variables:
 $ Manufacturer      : Factor w/ 32 levels "Acura","Audi",..: 1 1 2 2 3 4 4 4 4 5 ...
 $ Model             : Factor w/ 93 levels "100","190E","240",..: 49 56 9 1 6 24 54 74 73 35 ...
 $ Type              : Factor w/ 6 levels "Compact","Large",..: 4 3 1 3 3 3 2 2 3 2 ...
 $ Min.Price         : num  12.9 29.2 25.9 30.8 23.7 14.2 19.9 22.6 26.3 33 ...
 $ Price             : num  15.9 33.9 29.1 37.7 30 15.7 20.8 23.7 26.3 34.7 ...
 $ Max.Price         : num  18.8 38.7 32.3 44.6 36.2 17.3 21.7 24.9 26.3 36.3 ...
 $ MPG.city          : int  25 18 20 19 22 22 19 16 19 16 ...
 $ MPG.highway       : int  31 25 26 26 30 31 28 25 27 25 ...
 $ AirBags           : Factor w/ 3 levels "Driver & Passenger",..: 3 1 2 1 2 2 2 2 2 2 ...
 $ DriveTrain        : Factor w/ 3 levels "4WD","Front",..: 2 2 2 2 3 2 2 3 2 2 ...
 $ Cylinders         : Factor w/ 6 levels "3","4","5","6",..: 2 4 4 4 2 2 4 4 4 5 ...
 $ EngineSize        : num  1.8 3.2 2.8 2.8 3.5 2.2 3.8 5.7 3.8 4.9 ...
 $ Horsepower        : int  140 200 172 172 208 110 170 180 170 200 ...
 $ RPM               : int  6300 5500 5500 5500 5700 5200 4800 4000 4800 4100 ...
 $ Rev.per.mile      : int  2890 2335 2280 2535 2545 2565 1570 1320 1690 1510 ...
 $ Man.trans.avail   : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 1 1 1 1 ...
 $ Fuel.tank.capacity: num  13.2 18 16.9 21.1 21.1 16.4 18 23 18.8 18 ...
 $ Passengers        : int  5 5 5 6 4 6 6 6 5 6 ...
 $ Length            : int  177 195 180 193 186 189 200 216 198 206 ...
 $ Wheelbase         : int  102 115 102 106 109 105 111 116 108 114 ...
 $ Width             : int  68 71 67 70 69 69 74 78 73 73 ...
 $ Turn.circle       : int  37 38 37 37 39 41 42 45 41 43 ...
 $ Rear.seat.room    : num  26.5 30 28 31 27 28 30.5 30.5 26.5 35 ...
 $ Luggage.room      : int  11 15 14 17 13 16 17 21 14 18 ...
 $ Weight            : int  2705 3560 3375 3405 3640 2880 3470 4105 3495 3620 ...
 $ Origin            : Factor w/ 2 levels "USA","non-USA": 2 2 2 2 2 1 1 1 1 1 ...
 $ Make              : Factor w/ 93 levels "Acura Integra",..: 1 2 4 3 5 6 7 9 8 10 ... 

 

 

 

ggplot2는 신규 설치 및 호출이 필요한 패키지이므로 아래와 같은 사전 절차가 필요합니다.

 

> # ggplot2 설치 및 호출

> install.packages("ggplot2") > library(ggplot2) 

 

순서대로 하나씩 살펴보겠습니다.  함수 옵션을 바꿔줌에 따라서 x축, y축 결과가 어떻게 바뀌는지 살펴보시고, 필요로 하는 함수 옵션을 선택해서 사용하시면 되겠습니다.

 

(0) Default setting

 

> # default setting of x and y axis
> ggplot(Cars93, aes(x=MPG.city, y=MPG.highway)) +
+   geom_point(shape=21, colour="black", size=3) + 
+   ggtitle("default setting of x and y axis") 
 

 

 

 

 

(1) 1:1 의 비율로 x축과 y축 설정 : coord_fixed()

 

> # 1:1 proportion of x and y axis : coord_fixed()
> ggplot(Cars93, aes(x=MPG.city, y=MPG.highway)) +
+   geom_point(shape=21, colour="black", size=3) + 
+   coord_fixed() +
+   ggtitle("1:1 proportion of x and y axis : coord_fixed()")

 

 

 

 

 

 

(2) 일정한 간격으로 x축과 y축 설정 : scale_x_continuous(breaks=seq())

 

> # manual setting with fixed interval of x and y axis : scale_x_continuous(breaks=seq())
> ggplot(Cars93, aes(x=MPG.city, y=MPG.highway)) +
+   geom_point(shape=21, colour="black", size=3) + 
+   coord_fixed() +
+   scale_x_continuous(breaks=seq(0, 80, 5)) + 
+   scale_y_continuous(breaks=seq(0, 80, 5)) + 
+   ggtitle("manual setting with fixed interval of x and y axis : scale_x_continuous(breaks=seq())")

 

 

 

 

 

 

 

(3) 분석가 마음대로 x축과 y축 설정 : scale_x_continuous(breaks=c())

 

> # manual setting of x and y axis : scale_x_continuous(breaks=c())
> ggplot(Cars93, aes(x=MPG.city, y=MPG.highway)) +
+   geom_point(shape=21, colour="black", size=3) + 
+   coord_fixed() +
+   scale_x_continuous(breaks=c(10, 15, 20, 25, 30, 40)) + 
+   scale_y_continuous(breaks=c(20, 25, 30, 40, 50)) + 
+   ggtitle("manual setting of x and y axis : scale_x_continuous(breaks=c())")

 

 

 

 

함수 옵션을 바꿔줌에 따라서 x축, y축 결과가 어떻게 바뀌는지 살펴보시고, 필요로 하는 함수 옵션을 선택해서 사용하시면 되겠습니다.

 

많은 도움 되었기를 바랍니다.

 

 

728x90
반응형
Posted by Rfriend
,

그룹(집단, 요인) 간의 데이터 분포 형태, 변화 추이 등을 비교 분석하기에 유용한 방법으로 비교하려는 축을 기준으로 면을 분할하여 그래프를 그룹 간 비교하는 방법이 있습니다.

 

Lattice 패키지에서는 Trellis 를 사용하는데요, ggplot2 패키지에서는 facet_grid() 함수facet_wrap() 함수를 사용하여 면 분할을 구현할 수 있습니다.

 

Base Graphics 패키지에서는 par() 함수를 사용해서 면 분할을 지정해줄 수 있습니다만, x축과 y축의 scale이 들쭉날쭉해서 직접적으로 서로 비교하기가 곤란하거나, y축의 min, max 값이 그룹 간 숫자를 모두 감안해서 자동 설정되는 것이 아니다보니 분석가가 미리 y축 값의 범위를 계산해보고, 혹은 그려보고 나서 y축 값을 세팅해줘야 하므로 lattice나 ggplot2 대비 불편합니다.  따라서 집단간 비교를 위한 면 분할이 필요한 경우 ggplot2나 lattice 패키지를 권합니다.

 

MASS 패키지 내 무게(Weight), 고속도로연비(MPG.highway), 차종(Type, 범주형), 생산국가(Origin, 범주형) 의 4개 변수를 사용해서, x축에 무게(Weight), y축에 고속도로연비(MPG.highway), 그리고 면 분할의 기준으로 범주형 변수인 차종(Type)과 생산국가(Origin) 변수를 사용하겠습니다.

 

facet_grid()를 먼저 예제를 보이고, 그 후에 facet_wrap()의 예제를 들겠습니다.  두 함수가 비슷하면서도 조금 다릅니다.  분석가가 필요로 하는 아웃풋 이미지에 맞게 골라서 사용하면 되겠습니다.

 

 

(1) facet_grid()

 

> # facet_grid()
> ggplot(Cars93, aes(x=Weight, y=MPG.highway)) +
+   geom_point(shape=21, colour="black") +
+   facet_grid(Type ~ .)
 

 


 

> ggplot(Cars93, aes(x=Weight, y=MPG.highway)) +
+   geom_point(shape=21, colour="black") +
+   facet_grid(. ~ Type)

 

 

 

 


 

> ggplot(Cars93, aes(x=Weight, y=MPG.highway)) +
+   geom_point(shape=21, colour="black") +
+   facet_grid(Origin ~ Type)

 

 

 

 

 

 

 

(2) facet_wrap()

 

facet_wrap()는 ncol 또는 nrow 로 행 또는 열의 개수를 분석가가 지정할 수 있어서 좋은 점이 있습니다.

 

> # facet_wrap()
> ggplot(Cars93, aes(x=Weight, y=MPG.highway)) +
+   geom_point(shape=21, colour="black") +
+   facet_wrap( ~ Type, ncol=3)

 

 

 


 

> ggplot(Cars93, aes(x=Weight, y=MPG.highway)) +
+   geom_point(shape=21, colour="black") +
+   facet_wrap(Origin ~ Type, ncol=3)

 

 

 


 

> ggplot(Cars93, aes(x=Weight, y=MPG.highway)) +
+   geom_point(shape=21, colour="black") +
+   facet_wrap(Origin ~ Type, ncol=2)

 

 

 

 

많은 도움 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^

 

 

728x90
반응형
Posted by Rfriend
,

이전 포스팅에서 x축과 y축의 값에 따라 산점도 그리는 방법을 알아보았다면, 이번 포스팅에서는 여기에 더해서 z라는 제 3의 변수에 비례해서 점의 크기를 변화시켜서 그린 그래프가 버블 그래프 (Bubble Chart) 입니다.  산점도가 2차원의 그래프(단, 색깔이나 모양 조건을 추가하면 3차원 정보 제공 가능)라면, 버블 그래프 (Bubble Chart)는 3차원의 그래프가 되어 지면에 보다 많은 정보량을 제공할 수 있는 장점이 있습니다. 

 

ggplot2에서는 산점도, 점 그래프를 그리는 geom_point() 함수와 함께 scale_size_area() 함수를 같이 사용하면 버블 그래프 (Bubble Chart)를 그릴 수가 있습니다.

 

MASS 패키지의 Cars93 데이터 프레임 내에 차 모델명(Model), 차종(Type), 무게(Weight), 고속도로연비(MPG.highway), 가격(Price)의 5개 변수를 사용하여 버블 그래프를 그려보겠습니다.  데이터가 너무 많으면 버블 그래프를 그릴 때 겹쳐 보여서 보기 싫으므로 차종(Type)에서 "compact"와 "large"의 두 종만 선별해서 예를 들어보겠습니다.

 

> library(MASS)
> str(Cars93)
'data.frame':	93 obs. of  27 variables:
 $ Manufacturer      : Factor w/ 32 levels "Acura","Audi",..: 1 1 2 2 3 4 4 4 4 5 ...
 $ Model             : Factor w/ 93 levels "100","190E","240",..: 49 56 9 1 6 24 54 74 73 35 ...
 $ Type              : Factor w/ 6 levels "Compact","Large",..: 4 3 1 3 3 3 2 2 3 2 ...
 $ Min.Price         : num  12.9 29.2 25.9 30.8 23.7 14.2 19.9 22.6 26.3 33 ...
 $ Price             : num  15.9 33.9 29.1 37.7 30 15.7 20.8 23.7 26.3 34.7 ...
 $ Max.Price         : num  18.8 38.7 32.3 44.6 36.2 17.3 21.7 24.9 26.3 36.3 ...
 $ MPG.city          : int  25 18 20 19 22 22 19 16 19 16 ...
 $ MPG.highway       : int  31 25 26 26 30 31 28 25 27 25 ...
 $ AirBags           : Factor w/ 3 levels "Driver & Passenger",..: 3 1 2 1 2 2 2 2 2 2 ...
 $ DriveTrain        : Factor w/ 3 levels "4WD","Front",..: 2 2 2 2 3 2 2 3 2 2 ...
 $ Cylinders         : Factor w/ 6 levels "3","4","5","6",..: 2 4 4 4 2 2 4 4 4 5 ...
 $ EngineSize        : num  1.8 3.2 2.8 2.8 3.5 2.2 3.8 5.7 3.8 4.9 ...
 $ Horsepower        : int  140 200 172 172 208 110 170 180 170 200 ...
 $ RPM               : int  6300 5500 5500 5500 5700 5200 4800 4000 4800 4100 ...
 $ Rev.per.mile      : int  2890 2335 2280 2535 2545 2565 1570 1320 1690 1510 ...
 $ Man.trans.avail   : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 1 1 1 1 ...
 $ Fuel.tank.capacity: num  13.2 18 16.9 21.1 21.1 16.4 18 23 18.8 18 ...
 $ Passengers        : int  5 5 5 6 4 6 6 6 5 6 ...
 $ Length            : int  177 195 180 193 186 189 200 216 198 206 ...
 $ Wheelbase         : int  102 115 102 106 109 105 111 116 108 114 ...
 $ Width             : int  68 71 67 70 69 69 74 78 73 73 ...
 $ Turn.circle       : int  37 38 37 37 39 41 42 45 41 43 ...
 $ Rear.seat.room    : num  26.5 30 28 31 27 28 30.5 30.5 26.5 35 ...
 $ Luggage.room      : int  11 15 14 17 13 16 17 21 14 18 ...
 $ Weight            : int  2705 3560 3375 3405 3640 2880 3470 4105 3495 3620 ...
 $ Origin            : Factor w/ 2 levels "USA","non-USA": 2 2 2 2 2 1 1 1 1 1 ...
 $ Make              : Factor w/ 93 levels "Acura Integra",..: 1 2 4 3 5 6 7 9 8 10 ...
 
> levels(Cars93$Type)
[1] "Compact" "Large"   "Midsize" "Small"   "Sporty"  "Van" 
 
 

> table(Cars93$Type) Compact Large Midsize Small Sporty Van 16 11 22 21 14 9

 

 

> # dataset selection

> Cars93_sample <- subset(Cars93, 
+                         select = c("Model", "Type", "Weight", "MPG.highway", "Price"), 
+                         subset = (Type %in% c("Compact", "Large")))
> Cars93_sample
            Model    Type Weight MPG.highway Price
3              90 Compact   3375          26  29.1
7         LeSabre   Large   3470          28  20.8
8      Roadmaster   Large   4105          25  23.7
10        DeVille   Large   3620          25  34.7
12       Cavalier Compact   2490          36  13.4
13        Corsica Compact   2785          34  11.4
18        Caprice   Large   3910          26  18.8
20       Concorde   Large   3515          28  18.4
21        LeBaron Compact   3085          28  15.8
22       Imperial   Large   3570          26  29.5
25         Spirit Compact   2970          27  13.3
30         Vision   Large   3490          28  19.3
33          Tempo Compact   2690          27  11.3
38 Crown_Victoria   Large   3950          26  20.9
43         Accord Compact   3040          31  17.5
52       Town_Car   Large   4055          26  36.1
55            626 Compact   2970          34  16.5
58           190E Compact   2920          29  31.9
65         Altima Compact   3050          30  15.7
68        Achieva Compact   2910          31  13.5
71   Eighty-Eight   Large   3470          28  20.7
74        Sunbird Compact   2575          31  11.1
77     Bonneville   Large   3495          28  24.4
78            900 Compact   2775          26  28.7
82         Legacy Compact   3085          30  19.5
90         Passat Compact   2985          30  20.0
92            240 Compact   2985          28  22.7

 

 

ggplot2의 geom_point()와 scale_size_area() 함수를 사용하여 버블 그래프 (bubble chart)를 그려보겠습니다.  ggplot2는 별도의 설치와 호출이 필요한 패키지이므로 아래와 같이 install.packages()와 library()로 설치 및 호출을 먼저 해야 합니다.

 

> install.packages("ggplot2")
Installing package into ‘C:/Users/user/Documents/R/win-library/3.2’
(as ‘lib’ is unspecified)
trying URL 'http://cran.rstudio.com/bin/windows/contrib/3.2/ggplot2_1.0.1.zip'
Content type 'application/zip' length 2676272 bytes (2.6 MB)
downloaded 2.6 MB

package ‘ggplot2’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
	C:\Users\user\AppData\Local\Temp\RtmpKeoxEa\downloaded_packages
> library(ggplot2) 

 

 

 

x축에는 무게(Weight)를, y축에는 고속도로연비(MPG.highway)를, 원의 크기는 가격(Price)를 설정하였습니다.  그리고 겹치는 부분이 있어서 alpha=0.5 로 해서 반투명하게 하였습니다. scale_size_area 에서 원의 크기의 최대값(max)을 15개 한정을 지었으며, geom_text() 함수를 활용해 vjust=1로 해서 x축 값에 align되고 y값은 MPG.highway값에 살짝 조정을 가해서 label로는 모델명(Model) 변수값을 가져다가 라벨링을 하였습니다.

 

> # Bubble chart with scale_size_area and label
> ggplot(Cars93_sample, aes(x=Weight, y=MPG.highway)) + 
+   geom_point(aes(size=Price), shape=21, colour="grey90", fill="yellow", , alpha=0.5) +
+   scale_size_area(max_size = 15) + # 범례 없애려면 guide=FALSE
+   geom_text(aes(y=as.numeric(MPG.highway)-sqrt(Price)/10, label=Model), 
+             vjust=1, colour="grey40", size=3) + 
+   ggtitle("Bubble chart with scale_size_area and label") 
 
 

 

 

많은 도움이 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^ 

 

  

728x90
반응형
Posted by Rfriend
,

산점도는 두 변수간의 관계를 파악하는데 굉장히 유용한 시각화 방법입니다.  그리고 산점도 행렬은 다수의 변수들 간의 관계를 한눈에 파악하는데 유용한 시각화 방법이구요.

 

이전 포스팅에서

- ggplot2의 geom_point() 함수를 이용한 한개 변수의 산점도 그리기

- corrplot 패키지를 이용한 상관계수 행렬 그림 그리기

를 소개했었습니다.

 

ggplot2로 두 변수만 가지고 산점도는 유연하게 그릴 수 있는데요, 3개 이상의 변수를 가지고 산점도 행렬을 그리기는 매우 힘이 듭니다. (프로그래밍을 해야 합니다)  따라서 산점도 행렬은 plot() 함수를 써서 한방에 그리는 것이 제일 편하구요,

 

이번 포스팅에서는 Base Graphics 패키지 내에 pairs() 함수를 이용해서 산점도 행렬에 몇가지 사용자 정의 함수를 추가하여 히스토그램도 집어 넣고 상관계수 숫자도 포함시키는 방법을 소개하겠습니다.  산점도 행렬에 많은 추가 정보를 담을 수 있어서 매우 보기에 좋고 유용합니다. 사용자 정의 함수는 pairs() 도움말(help)을 참조하였습니다.

 

 

예제로 사용한 데이터는 뉴욕의 1973년도 공기의 질을 측정한 airquality 데이터셋의 Ozone, Solar.R, Wind, Temp 4개의 변수가 되겠습니다.

 

> str(airquality)
'data.frame':	153 obs. of  6 variables:
 $ Ozone  : int  41 36 12 18 NA 28 23 19 8 NA ...
 $ Solar.R: int  190 118 149 313 NA NA 299 99 19 194 ...
 $ Wind   : num  7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
 $ Temp   : int  67 72 74 62 56 66 65 59 61 69 ...
 $ Month  : int  5 5 5 5 5 5 5 5 5 5 ...
 $ Day    : int  1 2 3 4 5 6 7 8 9 10 ...
> 

> # 1~4번째 변수만 선택

> airquality_1 <- airquality[,c(1:4)]
> str(airquality_1)
'data.frame':	153 obs. of  4 variables:
 $ Ozone  : int  41 36 12 18 NA 28 23 19 8 NA ...
 $ Solar.R: int  190 118 149 313 NA NA 299 99 19 194 ...
 $ Wind   : num  7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
 $ Temp   : int  67 72 74 62 56 66 65 59 61 69 ... 

 

 

결측값이 있으면 상관계수를 구할 때 NA 값이 나오므로, 결측값 여부 확인하고 결측값이 있는 행은 삭제한 후에 산점도 행렬을 그려보겠습니다.

 

> # 결측값 개수 확인
> sum(is.na(airquality_1$Ozone)) # 37
[1] 37
> sum(is.na(airquality_1$Solar.R)) # 7
[1] 7
> sum(is.na(airquality_1$Wind)) # 0
[1] 0
> sum(is.na(airquality_1$Temp)) # 0
[1] 0
> 
> # 결측값 있는 상태에서 상관계수 계산했을 때
> cor(airquality_1)
        Ozone Solar.R       Wind       Temp
Ozone       1      NA         NA         NA
Solar.R    NA       1         NA         NA
Wind       NA      NA  1.0000000 -0.4579879
Temp       NA      NA -0.4579879  1.0000000
> 
> # 결측값 있는 행 전체 삭제
> airquality_2 <- na.omit(airquality_1)
> str(airquality_2)
'data.frame':	111 obs. of  4 variables:
 $ Ozone  : int  41 36 12 18 23 19 8 16 11 14 ...
 $ Solar.R: int  190 118 149 313 299 99 19 256 290 274 ...
 $ Wind   : num  7.4 8 12.6 11.5 8.6 13.8 20.1 9.7 9.2 10.9 ...
 $ Temp   : int  67 72 74 62 65 59 61 69 66 68 ...
 - attr(*, "na.action")=Class 'omit'  Named int [1:42] 5 6 10 11 25 26 27 32 33 34 ...
  .. ..- attr(*, "names")= chr [1:42] "5" "6" "10" "11" ...
> sum(is.na(airquality_2$Ozone)) # 0
[1] 0
> sum(is.na(airquality_2$Solar.R)) # 0
[1] 0 

 

 

 

산점도 행렬의 대각선에 히스토그램을 추가하는 사용자 정의 함수입니다.  pairs() 도움말(help)에 나와있는 사용자 정의함수 그대로 가져왔습니다.  아래 사용자 정의 함수를 카피해서 사용하시기 바랍니다.

 

## put histograms on the diagonal
panel.hist <- function(x, ...)
{
  usr <- par("usr"); on.exit(par(usr))
  par(usr = c(usr[1:2], 0, 1.5) )
  h <- hist(x, plot = FALSE)
  breaks <- h$breaks; nB <- length(breaks)
  y <- h$counts; y <- y/max(y)
  rect(breaks[-nB], 0, breaks[-1], y, col = "cyan", ...)

 

# source: help(pairs)

 

 

 

다음으로 산점도 행렬의 위쪽에 상관계수 숫자를 집어넣는 사용자 정의 함수입니다.  이 또한 pairs() 도움말(help)에 나와있는 사용자 정의함수 그대로 가져왔습니다.  아래 사용자 정의 함수를 카피해서 사용하시기 바랍니다.

 

## put (absolute) correlations on the upper panels,
## with size proportional to the correlations.
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 <- paste0(prefix, txt)
  if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
  text(0.5, 0.5, txt, cex = cex.cor * r)

 

# source : help(pairs)

 

 

 

다음으로 산점도에 선형 회귀선을 추가하는 사용자 정의 함수입니다.  이는 R Graphics Cookbook (원스턴 챙 지음, 이제원 옮김)을 참조하였습니다.  아래 사용자 정의 함수를 카피해서 사용하시기 바랍니다.

 

## put linear regression line on the scatter plot
panel.lm <- function(x, y, col=par("col"), bg=NA, pch=par("pch"),
                     cex=1, col.smooth="black", ...) {
  points(x, y, pch=pch, col=col, bg=bg, cex=cex)
  abline(stats::lm(y~x), col=col.smooth, ...)

 

 

 

이제 준비가 다 되었습니다.  airquality의 4개 변수 간의 산점도 행렬, 상관계수 숫자, 히스토그램을 하나의 도표로 나타내보겠습니다.

 

> ## 산점도 행렬(scatter-plot matrix), 상관계수(correlation), 히스토그램(histogram) > pairs(airquality_2, + lower.panel = panel.lm, # 아래쪽 산점도에 선형 직선 추가 + upper.panel = panel.cor, # 위쪽에는 상관계수 숫자 (상관계수에 크기 비례) + diag.panel = panel.hist, # 대각선에는 히스토그램 + pch="*", # 점 모양은 * 로 + main = "scatter-plot matrix, correlation coef., histogram" + )

 

 

 

 

 

 

보너스로, pairs() 함수를 사용해서 범주(그룹)별로 점의 색깔을 달리하는 방법도 소개하겠습니다.  이 역시 pairs() 함수 도움말(help)에 있는 R script 를 가져왔습니다.  도움말(help)이 정말 도움이 많이 됩니다. ^^  사용한 데이터는 그 유명한 Iris 데이터가 되겠습니다.

 

> # 범주(그룹)을 색깔로 구분하여 산점도 행렬 그리기
> pairs(iris[1:4], main = "Anderson's Iris Data -- 3 species",
+       pch = 21, bg = c("red", "green3", "blue")[unclass(iris$Species)])

 

 

 * R script source : help(pairs)

 

많은 도움 되셨기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^

 

728x90
반응형
Posted by Rfriend
,