R분석을 하다 보면 데이터 전처리 라든지 그래프 그리기, 혹은 모형 개발/ update 등을 하는데 있어 반복 작업을 하는 경우가 있습니다. 

 

이때 대상 데이터셋이라든지 변수, 혹은 조건 등을 조금씩 바꿔가면서 반복 작업을 (반)자동화 하고 싶을 때 유용하게 사용할 수 있는 것이 사용자 정의 함수 (User Defined Function) 입니다. 

 

만약 사용자 정의 함수를 사용하지 않는다면 특정 부분만 바뀌고 나머지는 동일한 프로그램이 매우 길고 복잡하고 산만하게 늘어세울 수 밖에 없게 됩니다.  반면 사용자 정의 함수를 사용하면 사용자 정의 함수 정의 후에 바뀌는 부분만 깔끔하게 사용자 정의 함수의 입력란에 바꿔서 한줄 입력하고 실행하면 끝입니다.  반복작업이 있다 싶으면 손과 발의 노가다를 줄이고 작업/분석 시간을 줄이는 방법, 프로그래밍을 간결하고 깔끔하게 짜는 방법으로 사용자 정의 함수를 사용할 여지가 있는지 살펴볼 필요가 있겠습니다.

 

 

 

 

 

사용자 정의 함수는

 

 

function_name <- function( arg1, arg2, ... ) {

                                                           expression

                                                           return( object)

                                                         }

 

 

의 형식을 따릅니다.

 

몇 가지 예을 들어서 설명해보겠습니다.

 

 

1) 평균(mean), 표준편차(standard deviation), min, max 계산 사용자 정의 함수
    (User defined function of statistics for continuous variable)

 

 

> # 평균, 표준편차, min, max 계산 > > stat_function <- function(x) { + x_mean = mean(x) + x_sd = sd(x) + x_min = min(x) + x_max = max(x) + x_summary = list(x_mean=x_mean, x_sd=x_sd, x_min=x_min, x_max=x_max) + return(x_summary) + } > > stat_function(x = Cars93$MPG.highway) $x_mean [1] 29.08602 $x_sd [1] 5.331726 $x_min [1] 20 $x_max [1] 50 > # summary() 함수와 비교 > summary(Cars93$MPG.highway) Min. 1st Qu. Median Mean 3rd Qu. Max. 20.00 26.00 28.00 29.09 31.00 50.00

 

 

 

 

2) 산점도 그래프 그리기 사용자 정의 함수 (User defined function of scatter plot)

 

> # 산점도 그래프 그리기 함수 (scatter plot)
> plot_function <- function(dataset, x, y, title) {
+   attach(dataset)
+   plot(y ~ x, dataset, type="p", 
+        main = title)
+   detach(dataset)

 

 

> plot_function(dataset=Cars93, x=MPG.highway, y=Weight, title="Scatter Plot of MPG.highway & Weight")

 

 

> plot_function(dataset=Cars93, x=Price, y=Horsepower, title="Scatter Plot of Price & Horsepower")
 

 

 

 

위의 기초통계량은 summary() 함수를 사용하면 되고 산포도도 plot() 함수를 쓰는 것과 별 차이가 없어보여서 사용자 정의 함수를 쓰는 것이 뭐가 매력적인지 잘 이해가 안갈 수도 있을 것 같습니다.  하지만 만약 기초 통계량을 뽑아서 txt 파일로 외부로 내보내기를 하고, x 변수를 바꿔가면서 loop를 돌려서 반복적으로 기초 통계량을 뽑고 이것을 계속 txt 파일로 외부로 내보내기를 하되, 앞서 내보냈던 파일에 계속 append 를 해가면서 결과값을 저장한다고 할때는 위의 사용자 정의 함수를 사용하는 것이 정답입니다. 

 

그래프도 변수명의 일부분을 바꿔가면서 그래프를 그리고 싶을 때는 paste() 함수를 적절히 사용하면 사용자 정의 함수를 더욱 강력하게 사용할 수 있게 됩니다.  응용하기 나름이고, 사용 가능한 경우가 무궁무진한데요, 이번 포스팅에서는 사용자 정의 함수의 기본 뼈대에 대해서만 간략히 살펴 보았습니다.

 

참고로, 사용자 정의 함수를 정의할 때 아래처럼 function(x, y, ...) 의 파란색 생략부호 점을 입력하면 나중에 사용자 정의 함수에서 정의하지 않았던 부가적인 옵션들을 추가로 덧붙여서 사용할 수 있어서 유연성이 높아지는 효과가 있습니다.

function_name <- function(x, y, ...) {

expresstion

return(object)

}

 

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

 

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

 

728x90
반응형
Posted by Rfriend
,

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

 

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

 

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 program을 짜보도록 하겠습니다.

 

 

 

 


  • 하나의 값에 대한 판단인 경우 : 

    if( 조건1 ) {
              표현식 1
    } else if (조건2) {
              표현식 2
    } else {
              표현식 3
    }

  

[ 짝수, 홀수 여부 판단 프로세스 ]

 

 

(1) 하나의 논리값에 대한 판단인 경우 : if()

 

> ## 하나의 논리값에 대한 판단
> # if()
> x1 <- c(4)
> if (x1 %% 2 == 0) {
+   y1 = c("Even Number")
+   print(y1)
+ } else {
+     y1 = c("Odd Number")
+     print(y1)
+ }
[1] "Even Number"

 

 

> x2 <- c(5)
> if (x2 %% 2 == 0) {
+   y2 = "Even Number"
+   print(y2)
+ } else {
+   y2 = "Odd Number"
+   print(y2)
+ }
[1] "Odd Number"
 

위의 2개의 예에서는 x1 이 4일 때 "Even Number"라고 판단했고, x2가 5일 때 "Odd Number"라고 잘 판단하였습니다.

 

하지만, 아래의 예제처럼 두개 이상의 논리값 벡터를 사용하는 경우에는 오류가 발생하게 되며, 아래 예제에서 보면 1~5까지 숫자 중에서 제일 처음으로 나오는 1에만 아래의 조건연산 프로그램이 적용되었고 두번째부터는 적용이 안되었습니다.  이럴 때는 ifelse() 문을 사용하여야 합니다

 

> # Error
> x3 <- c(1, 2, 3, 4, 5)
> if (x3 %% 2 == 0) {
+   y3 = "Even Number"
+   print(y3)
+ } else {
+   y3 = "Odd Number"
+   print(y3)
+ }
[1] "Odd Number"
Warning message:
In if (x3%%2 == 0) { :
  the condition has length > 1 and only the first element will be used

 



 

(2) 두개 이상의 논리값 벡터에 대한 판단 : ifelse()

 

  • 두개 이상의 논리값 벡터에 대한 판단인 경우 :

    ifelse( 조건1, 표현식1, 
          ifelse( 조건2, 표현식2, 
                 ifelse( 조건3, 표현식3, 표현식4)
                 ) 
           )
  •  

    위와 동일하게 1~5의 숫자에 대해서 이번에는 ifelse() 문을 사용해서 짝수, 홀수 여부를 판단하게 하고, 이를 데이터프레임 구조로 변환해서 view해보겠습니다.

     

    > ## vector 에 대한 판단
    > # 홀수/짝수 여부 판단 : ifelse( condition, expression 1, expression 2 )
    > x <- c(1, 2, 3, 4, 5)
    > z <- ifelse(x%%2 == 0, "Even Number", "Odd Number")
    > xz <- data.frame(x, z)
    > xz
      x           z
    1 1  Odd Number
    2 2 Even Number
    3 3  Odd Number
    4 4 Even Number
    5 5  Odd Number

     

     

     


     

     

    이번에는 양수, 0, 음수 인지 여부를 판단한 후 원래 벡터와 판단하는 프로그램을 ifelse()를 사용하여 짜보도록 하겠습니다.

     

    [ 양수, 0, 음수 인지 여부 판단하는 프로세스 ]

     

     

    > # 양수, 0, 음수인지 여부 판단 : ifelse( condition, expression 1, expression 2 ) > x <- c(-2, -1, 0, 1, 2) > y <- ifelse( x > 0, "Positive", + ifelse( x == 0, "Zero", "Negative") + ) > > xy <- data.frame(x, y) > > xy x y 1 -2 Negative 2 -1 Negative 3 0 Zero 4 1 Positive 5 2 Positive 

     

     


     

    To 산낙지님,

    제가 가족 여행다녀오느라 이제서야 집에 와서 댓글 달려고 막 하는 와중에...댓글을 삭제하셨네요. ^^;

    3가지 조건을 주어서 1, 0 혹은 yes, no 범주형 dummy 변수를 생성하는 방법은 아래를 참고하세요.

    MASS 패키지의 Cars93데이터프레임을 가지고 예를 들었습니다.

    [예제] "차종(Type)이 "Campact" 이고 & 가격(Price)이 16이하이고 & 고속도로연비(MPG.highway)가 30이상이면 1, 그 외는 모두 0인 변수 sub_yn 을 만드시오"

    ## Making dummy variable using ifelse() and transform()
    library(MASS)
    str(Cars93)
    summary(Cars93$Price)
    summary(Cars93$MPG.highway)

    Cars93 <- transform(Cars93,
                               sub_yn = ifelse(Type == c("Compact")
                                                   & Price <= 16
                                                   & MPG.highway >= 30, 1, 0))

     

     

     

     

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

     

     

    728x90
    반응형
    Posted by Rfriend
    ,

    R이 통계분석 툴이자 그래픽을 위한 훌륭한 툴이면서도, 동시에 프로그래밍 언어(programming language)로서도 매우 훌륭하답니다.  반복적인 작업(Loop process)을 해야 하는 경우나, 분석가가 알고리즘을 만들어서 자동화할 수 있는 사용자 정의 함수(User defined function) 를 잘 사용한다면 소위 말하는 시간 잡아먹는 노가다를 컴퓨터에게 대신 시킬 수 있게 됩니다. 

     

    손발이 편하고 싶고, 귀한 시간을 아끼고 싶다면 R 프로그래밍에 대해 익혀두는게 유용할 것입니다.  게다가, R이 데이터 변환/처리/분석/그래프 까지 두루 섭렵하고 있다보니 "데이터 기반의 프로그래밍"이 필요한 일이라면 R이 제격이라고 하겠습니다.

     

    이번 포스팅에서는 for()와 while() 함수를 사용하여 반복 연산 프로그래밍 (Loop process programming) 하는 방법을 몇 개 예를 들어 소개하겠습니다.

     

     

    [ Loop Process Diagram ]

     

     

     

     

    (1) y= 10 + 5*x 함수에 x를 1부터 10까지 1씩 더해가면서 연산하고 y값을 순차적으로 프린트

         : for (var in seq) {expression}

     

    > # x 1:10, y = 10 + 5*x
    > for ( x in 1:10) {
    +   y = 10 + 5*x
    +   print(y)
    + }
    [1] 15
    [1] 20
    [1] 25
    [1] 30
    [1] 35
    [1] 40
    [1] 45
    [1] 50
    [1] 55
    [1] 60 

     

     

    (2) 1~10까지의 1씩 늘려가면서 누적합 구하고, 순차적으로 프린트하기

        : for (var in seq) {expression}

     

     
    > # 1~10까지 누적합 구하기 (cummulative sum by for) : for (var in seq) { expression }
    > y <- 0
    > for(i in 1:10) {
    +      y = y + i
    +      cat("cummulative summation from 0 to ", i, " is ", y, "\n", sep="")
    +    }
    cummulative summation from 0 to 1 is 1
    cummulative summation from 0 to 2 is 3
    cummulative summation from 0 to 3 is 6
    cummulative summation from 0 to 4 is 10
    cummulative summation from 0 to 5 is 15
    cummulative summation from 0 to 6 is 21
    cummulative summation from 0 to 7 is 28
    cummulative summation from 0 to 8 is 36
    cummulative summation from 0 to 9 is 45
    cummulative summation from 0 to 10 is 55
     

     

    참고로, cat 은 텍스트를 받아다가 콘솔에 프린트해주는 기능을 합니다.

    "\n" 은 줄바꿈 설정하는 파라미터입니다.

    sep="" 는 cat() 함수 안에 큰따옴표로 들어가 있는 텍스트 문자열 혹은 'i', 'z' 객체를 연결할 때 구분자를 지정해주는 것입니다. sep="" 이므로 아무것도 없이 그냥 붙여서 연결시키라는 뜻이구요, 만약 sep="__" 라고 under-bar 2개로 지정해주면 첫번째 줄이

    cummulative summation from 0 to __1__ is __1

    처럼 프린트 되었을 것입니다.

     

     

     

    (3) 1~10까지의 1씩 늘려가면서 누적합 구하고, 순차적으로 프린트하기

        : while (condition) {expression}

     

    while() 문은 조건을 걸고 싶거나 반복회수를 미리 파악하기 어려운 경우에 사용하면 유용합니다.

     

     
    > # 1~10까지 누적합 구하기 (cummlative sum by while) : while(condition) { expression }
    > z <- 0
    > i <- 1
    > while( i <= 10) {
    +      z = z + i
    +      cat("cummulative summation from 0 to ", i, " is ", z, "\n", sep="") 
    +      i = i + 1
    +    }
    cummulative summation from 0 to 1 is 1
    cummulative summation from 0 to 2 is 3
    cummulative summation from 0 to 3 is 6
    cummulative summation from 0 to 4 is 10
    cummulative summation from 0 to 5 is 15
    cummulative summation from 0 to 6 is 21
    cummulative summation from 0 to 7 is 28
    cummulative summation from 0 to 8 is 36
    cummulative summation from 0 to 9 is 45
    cummulative summation from 0 to 10 is 55
     

     

     

     


     

     

    예를 들어, 1부터 시작해서 1씩 늘려가면서 3을 더해가는 것(y = y + 3)을 반복하는데, 단 5 이하일 때까지만 반복시키는 조건이 있을 때,

     - while(condition)

     - while(TRUE/FALSE) { if () break }

     - repeat { if () break }

    의 3가지 방법을 알아보겠습니다.  아래의 (4) ~ (6)번 프로그래밍 예제는 로직과 결과가 동일합니다.

     

    (4) while(condition)

     

    > # while(condition) => stop
    > i <- 1
    > while( i <= 5 ) {
    +   i <- i+3
    + }
    > 
    > i
    [1] 7 

     

     

     

    (5) while(TRUE/FALSE) { if () break }

     

    > # while(TRUE/FALSE) { if () break } => stop
    > j <- 1
    > while(TRUE) {
    +   j <- j+3
    +   if (j > 5) break
    + }
    > 
    > j
    [1] 7

     

    처음에 j <- 1로 할당되었습니다. 

    그 다음에 while() 문으로 넘어가서요, j <- j+3 이므로 j <- 1+3 가 되어서 j에 4가 새로 할당(덮어쓰기)이 되었습니다.  if (j > 5) break 인데요, 여기서 j는 4이므로 if (j > 5) 조건에서 FALSE 가 됩니다. 따라서 break하지 않고 loop 를 계속 돌게 됩니다(not break, but continue loop). 

    그럼 다시 j <- j+3 으로 돌아가서 다시 연산을 수행합니다. 방금 전 연산에서 j가 4로 재할당 되었었지요? 그러므로 j+3 = 4+3 = 7로서 j에 7이 재할당 (덮어쓰기) 됩니다.

    if (j > 5) 조건에서 if (7 > 5) 로서 TRUE 가 되었으므로 break 하게 됩니다.

    j 를 프린트해보면 '7'이 됩니다.

     

     

     

    (6) repeat { if () break }

     

    > # repeat { if () break } => stop > k <- 1 > repeat { + k <- k+3 + if (k > 5) break + } > > k [1] 7

     

     

    위의 (5)번, (6)번 예에서 보면 while 문에는 TRUE/FALSE 의 불리언 상태값이 있습니다만, repeat 문에는 불리언 상태값 없이 break 를 사용해서 조건을 만족하면 반복을 중지시키는 차이점이 있습니다.

     

     

     


     

    아래의 프로그램 예는 repeat 함수를 이용해서 factorial(i) 값이 1,000,000,000,000 보다 작을 때까지는 계산 순차적으로 1씩 i를 증가시켜가면서 계산을 하고 프린트를 하다가, 1조보다 커지면 stop하라는 명령문입니다.

     

     
    > i <- 1
    > repeat {
    +   factorial_value <- factorial(i)
    +   cat("factorial(", i, ") = ", factorial_value, "\n", sep="")
    +   if (factorial_value > 1000000000000) break
    +   i <- i+1
    + }
    factorial(1) = 1
    factorial(2) = 2
    factorial(3) = 6
    factorial(4) = 24
    factorial(5) = 120
    factorial(6) = 720
    factorial(7) = 5040
    factorial(8) = 40320
    factorial(9) = 362880
    factorial(10) = 3628800
    factorial(11) = 39916800
    factorial(12) = 479001600
    factorial(13) = 6227020800
    factorial(14) = 87178291200
    factorial(15) = 1.307674e+12

     

     

     

     

    factorial(i) 값이 '0'이 100개 붙은 값(우리나라말로 이걸 명칭하는 단위가 없죠? 어마무시 큰 수? ^^')보다 작으면 계속 i 값을 1씩 증가시키면서 계산하다가, '0'이 100개 붙은 값보다 커지면 stop 하라는 명령문은 아래와 같습니다.

     

    > i <- 1
    > repeat {
    +   factorial_value <- factorial(i)
    +   cat("factorial(", i, ") = ", factorial_value, "\n", sep="")
    +   if (factorial_value > 1e+100) break
    +   i <- i+1
    + }
    factorial(1) = 1
    factorial(2) = 2
    factorial(3) = 6
    factorial(4) = 24
    factorial(5) = 120
    factorial(6) = 720
    factorial(7) = 5040
    factorial(8) = 40320
    factorial(9) = 362880
    factorial(10) = 3628800
    factorial(11) = 39916800
    factorial(12) = 479001600
    factorial(13) = 6227020800
    factorial(14) = 87178291200
    factorial(15) = 1.307674e+12
    factorial(16) = 2.092279e+13
    factorial(17) = 3.556874e+14
    factorial(18) = 6.402374e+15
    factorial(19) = 1.216451e+17
    factorial(20) = 2.432902e+18
    factorial(21) = 5.109094e+19
    factorial(22) = 1.124001e+21
    factorial(23) = 2.585202e+22
    factorial(24) = 6.204484e+23
    factorial(25) = 1.551121e+25
    factorial(26) = 4.032915e+26
    factorial(27) = 1.088887e+28
    factorial(28) = 3.048883e+29
    factorial(29) = 8.841762e+30
    factorial(30) = 2.652529e+32
    factorial(31) = 8.222839e+33
    factorial(32) = 2.631308e+35
    factorial(33) = 8.683318e+36
    factorial(34) = 2.952328e+38
    factorial(35) = 1.033315e+40
    factorial(36) = 3.719933e+41
    factorial(37) = 1.376375e+43
    factorial(38) = 5.230226e+44
    factorial(39) = 2.039788e+46
    factorial(40) = 8.159153e+47
    factorial(41) = 3.345253e+49
    factorial(42) = 1.405006e+51
    factorial(43) = 6.041526e+52
    factorial(44) = 2.658272e+54
    factorial(45) = 1.196222e+56
    factorial(46) = 5.502622e+57
    factorial(47) = 2.586232e+59
    factorial(48) = 1.241392e+61
    factorial(49) = 6.082819e+62
    factorial(50) = 3.041409e+64
    factorial(51) = 1.551119e+66
    factorial(52) = 8.065818e+67
    factorial(53) = 4.274883e+69
    factorial(54) = 2.308437e+71
    factorial(55) = 1.26964e+73
    factorial(56) = 7.109986e+74
    factorial(57) = 4.052692e+76
    factorial(58) = 2.350561e+78
    factorial(59) = 1.386831e+80
    factorial(60) = 8.320987e+81
    factorial(61) = 5.075802e+83
    factorial(62) = 3.146997e+85
    factorial(63) = 1.982608e+87
    factorial(64) = 1.268869e+89
    factorial(65) = 8.247651e+90
    factorial(66) = 5.443449e+92
    factorial(67) = 3.647111e+94
    factorial(68) = 2.480036e+96
    factorial(69) = 1.711225e+98
    factorial(70) = 1.197857e+100

     

     

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

     

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

     

     

    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
    ,