'sd=1))'에 해당되는 글 1건

  1. 2015.09.07 R ggplot2 연속확률분포 곡선, stat_function()

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

 

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

 

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
,