'균등분포'에 해당되는 글 2건

  1. 2015.09.19 R 균등분포 (uniform distribution) : unif() 5
  2. 2015.09.07 R ggplot2 연속확률분포 곡선, stat_function()

연속형 확률분포 (Continuous probability distribution)에는

 

 - 정규분포 (normal distribution)

   : norm()

 

 - 균등분포 (uniform distribution)

   : unif()

 

  - 지수분포 (exponential distribution)

   : exp()

 

 - t-분포 (t-distribution)

   : t()

 

 - F-분포 (F-distribution)

   : f()

 

  - 카이제곱분포(chisq-distribution)

   : chisq()

 

등이 있습니다.  

 

 

이번 포스팅에서는 균등분포(uniform distribution)에 대해서 알아보겠습니다.  균등분포(uniform distribution)은 연속형 확률 분포 중에서 가장 간단한 형태로서, 구간 [mi=a, max=b]에서 값이 균등하게 퍼져 있는 집단, 일어날 확률이 균등한 분포를 말합니다. 

 

가령, 김포공항에서 제주도 공항까지 비행기로 이륙에서 착륙까지 걸리는 총 비행시간이 1시간~1시간5분 사이라고 하면, 0시~59분59초까지는 비행기가 도착할 확률이 0, 1시간~1시간5분 사이에 도착할 확률은 1, 1시간 5분 이후는 다시 확률이 0이 되는 균등분포를 따른다고 할 수 있겠습니다.

 

 

 

 

 

 

 

R에서 사용하는 균등분포 함수(uniform distribution function) 및 파라미터(parameter)들은 아래와 같으며, 필요한 함수, 파라미터를 가져다 사용하면 되겠습니다.

 

 

 함수 구분

 균등분포 함수/파라미더

 unif()

  밀도함수

  (density function)

 d

  dunif(x, min, max)

  누적분포함수

 (cumulative distribution function)

 p

  punif(q, min, max, lower.tail=TRUE/FALSE)

  분위수 함수

 (quantile function)

 q

  qunif(p, min, max, lower.tail=TRUE/FALSE)

  난수 발생

 (random number generation)

 r

  runif(n, min, max)

 

 

 

 

(1) 균등분포 그래프(uniform distribution plot) : fun = dunif

 

ggplot2의 fun= dunif() 함수를 사용해서 균등분포를 그래프로 그려보면 아래와 같이 특정 구간 [a, b]에서 확률이 균등함을 알 수 있습니다.

 

 

> library(ggplot2)

> # uniform distribution plot (min=0, max=10) > # 균등분포 : 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)")

 

 

 

 

 

 

 

(2) 누적 균등분포 그래프(cumulative uniform distribution plot) : fun = punif

누적 균등분포 그래프를 그려보면 아래와 같습니다.

 

 

> # (2) 누적균등분포 함수 그래프 (Cumulative Uniform distribution plot) : fun = punif > ggplot(data.frame(x=c(-2,20)), aes(x=x)) + + stat_function(fun=punif, args=list(min = 0, max = 10), colour="black", size=1) + + ggtitle("Cumulative Uniform Distribution of (min=0, max=10)")

 

 

 

 

 

 

(3) 누적 균등분포 함수의 확률 값 계산 : punif()

 

 

> # (3) 누적 균등분포함수(cumulative uniform distribution function) 확률 값 계산 : punif() > # : punif(q, min, max, lower.tail = TRUE/FALSE) > punif(3, min=0, max=10, lower.tail=TRUE) [1] 0.3 > >

> # Uniform Distribution of (min=1, max=10), x from 0 to 3"

> ggplot(data.frame(x=c(-2,20)), aes(x=x)) + + stat_function(fun=dunif, args=list(min = 0, max = 10), colour="black", size=1) + + annotate("rect", xmin=0, xmax=3, ymin=0, ymax=0.1, alpha=0.2, fill="yellow") + + ggtitle("Uniform Distribution of (min=1, max=10), x from 0 to 3")

 

 

 

 

 

(4) 균등분포 분위수 함수 값 계산 : qunif(p, min, max, lower.tail=TRUE/FALSE)

 

이전 포스팅의 정규분포와는 함수는 qunif()로 동일하지만 괄호 안의 parameter 들은 다릅니다.

(참고: 정규분포에서는 qunif(p, mean, sd, lower.tail=T/F)

 

 
> # (4) 분위수 함수 : qunif(p, min, max, lower.tail=TRUE/FALSE)
> qunif(0.3, min=0, max=10, lower.tail = TRUE)
[1] 3

 

 

 

 

(5) 난수 발생 : runif(n, min, max)

 

난수는 매번 실행할 때마다 바뀌므로 제가 아래에 제시한 것과는 다른 숫자, 다른 그래프가 그려질 것입니다만, 형태는 균등분포를 띠는 유사한 모양이 될 것입니다.

 

 

> ru_100 <- runif(n=100, min=0, max = 10)
> ru_100

 

 [1] 7.33957568 2.78596723 6.30797744 5.01438337 6.57949706 5.90883342 3.51446293 9.28736811
  [9] 9.55213668 5.59377524 4.71003185 3.29525512 0.25759555 9.40326151 6.56466466 2.44973803
 [17] 4.88714900 3.10710648 3.84375758 8.55017741 3.09487276 0.13411621 0.44285713 8.90632265
 [25] 0.07968823 5.03465390 4.64601169 1.23565062 4.81310463 1.59225023 7.03799510 0.68870704
 [33] 4.03014086 9.97756283 5.55815726 2.01819345 7.00497545 8.50399118 2.29608430 2.92359120
 [41] 0.85656712 6.52544881 6.37193951 6.15247601 5.29502105 7.68988134 6.37691223 0.37387705
 [49] 6.89023959 1.65049129 3.75195268 7.97220092 6.50160025 9.52491436 1.70569894 9.80475205
 [57] 0.24770673 8.47412000 4.66718922 2.52269224 2.81985175 8.79845402 6.03852213 8.10848875
 [65] 1.10510449 9.35548906 1.83535387 0.47889795 6.54578585 1.61742080 4.51840400 3.99912651
 [73] 4.82545376 4.04589108 0.71750065 7.56085867 1.22887762 2.97822070 5.14541682 3.59126885
 [81] 5.00911758 1.02152702 7.78324707 4.69437196 1.13090493 3.70933500 0.03173870 5.74159309
 [89] 2.68879279 3.36398725 9.34593590 6.18818473 9.43490689 5.82578697 4.49576854 2.90029081
 [97] 3.34726356 7.19013351 9.97276521 9.39421932

 

 

> # density plot of runif(n=100, min=0, max = 10) & adding line of 0.1 uniform probability

> hist(ru_100, freq=FALSE, breaks=10, col="yellow")

> abline(h=0.1, lty=3, lwd=3, col="red")

 

 

 

 

 

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

 

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

 

 

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
,