R에서 정규 분포를 그리는 방법


R에서 정규 분포를 그리려면 기본 R을 사용하거나 ggplot2와 같은 보다 정교한 패키지를 설치할 수 있습니다.

BaseR 사용

다음은 Base R을 사용하여 정규 분포 도표를 생성하는 세 가지 예입니다.

예 1: 평균 = 0이고 표준 편차 = 1인 정규 분포

평균 = 0이고 표준 편차 = 1인 정규 분포 도표를 만들려면 다음 코드를 사용할 수 있습니다.

 #Create a sequence of 100 equally spaced numbers between -4 and 4
x <- seq(-4, 4, length=100)

#create a vector of values that shows the height of the probability distribution
#for each value in x
y <- dnorm(x)

#plot x and y as a scatterplot with connected lines (type = "l") and add
#an x-axis with custom labels
plot(x,y, type = "l", lwd = 2, axes = FALSE, xlab = "", ylab = "")
axis(1, at = -3:3, labels = c("-3s", "-2s", "-1s", "mean", "1s", "2s", "3s"))

그러면 다음 플롯이 생성됩니다.

예 2: 평균 = 0이고 표준 편차 = 1인 정규 분포(코드 적음)

또한 xy를 정의하지 않고 다음 코드를 사용하여 “곡선” 함수를 사용하여 정규 분포 플롯을 만들 수도 있습니다.

 curve(dnorm, -3.5, 3.5, lwd=2, axes = FALSE, xlab = "", ylab = "")
axis(1, at = -3:3, labels = c("-3s", "-2s", "-1s", "mean", "1s", "2s", "3s"))

이것은 정확히 동일한 플롯을 생성합니다.

예제 3: 사용자 정의 평균과 표준편차를 사용한 정규분포

사용자 정의 평균 및 표준 편차를 사용하여 정규 분포 도표를 생성하려면 다음 코드를 사용할 수 있습니다.

 #define population mean and standard deviation
population_mean <- 50
population_sd <- 5

#define upper and lower bound
lower_bound <- population_mean - population_sd
upper_bound <- population_mean + population_sd

#Create a sequence of 1000 x values based on population mean and standard deviation
x <- seq(-4, 4, length = 1000) * population_sd + population_mean

#create a vector of values that shows the height of the probability distribution
#for each value in x
y <- dnorm(x, population_mean, population_sd)

#plot normal distribution with customized x-axis labels
plot(x,y, type = "l", lwd = 2, axes = FALSE, xlab = "", ylab = "")
sd_axis_bounds = 5
axis_bounds <- seq(-sd_axis_bounds * population_sd + population_mean,
                    sd_axis_bounds * population_sd + population_mean,
                    by = population_sd)
axis(side = 1, at = axis_bounds, pos = 0)

그러면 다음 플롯이 생성됩니다.

ggplot2 사용

R에서 정규 분포도를 만드는 또 다른 방법은 ggplot2 패키지를 사용하는 것입니다. 다음은 ggplot2를 사용하여 정규 분포 플롯을 생성하는 두 가지 예입니다.

예 1: 평균 = 0이고 표준 편차 = 1인 정규 분포

평균 = 0이고 표준 편차 = 1인 정규 분포 도표를 만들려면 다음 코드를 사용할 수 있습니다.

 #install (if not already installed) and load ggplot2
if(!(require(ggplot2))){install.packages('ggplot2')}

#generate a normal distribution plot
ggplot(data.frame(x = c(-4, 4)), aes(x = x)) +
stat_function(fun = dnorm)

그러면 다음 플롯이 생성됩니다.

예시 2: ‘mtcars’ 데이터 세트를 사용한 정규 분포

다음 코드는 mtcars 임베디드 R 데이터 세트의 갤런당 마일 열에 대한 정규 분포를 생성하는 방법을 보여줍니다.

 ggplot(mtcars, aes(x = mpg)) +
stat_function(
fun = dnorm,
args = with(mtcars, c(mean = mean(mpg), sd = sd(mpg)))
) +
scale_x_continuous("Miles per gallon")

그러면 다음 플롯이 생성됩니다.

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다