로지스틱 회귀분석 그림

library(ggplot2)

## 먼저 가장 중심이 되는 직선의 함수를 정의한다. 
line1 <- function(x) 
{
   y <- 1 + .5*x
   return(y)
}

## 직선 위를 지나는 점을 평균으로 지니는 정규분포의 점을 생성한다. 
y <- seq(-3, 3, 0.01)
x <- dnorm(y, mean = 0, sd = .75)
norm0 <- data.frame(x, y)

norm1 <- norm0
norm2 <- norm0
norm3 <- norm0

## 정해진 위치에 맞게 평행이동한다. 
norm1$x <- norm0$x + 2
norm1$y <- norm0$y + 2

norm2$x <- norm0$x + 5
norm2$y <- norm0$y + 3.5

norm3$x <- norm0$x + 7
norm3$y <- norm0$y + 4.5

## y=1이 되는 정규분포 아래 영역을 정의하는 점을 생성한다. 
norm1.a <- subset(norm1, y>= 2.5)
norm2.a <- subset(norm2, y>= 2.5)
norm3.a <- subset(norm3, y>= 2.5)

##기본이 되는 직선을 생성한다. 
ggplot(data.frame(x=c(-1, 9), y=c(-3, 1.5)), aes(x=x, y=y)) + 
      stat_function(fun = line1, size = 1, color = "RED") +

## 직선 위의 정규분포를 그린다. 
   geom_point(data = norm1, size = 0.1, color = "grey20") + 
   geom_point(data = norm2, size = 0.1, color = "grey20") +  
   geom_point(data = norm3, size = 0.1, color = "grey20") + 

## 미리 정의된 영역에 따라 y=1 이상의 영역을 음영으로 표시한다. 
   geom_segment(data = norm1.a, aes(yend = y), xend=2, color = "grey50", alpha = 0.25) +
   geom_segment(data = norm2.a, aes(yend = y), xend=5, color = "grey50", alpha = 0.25) +
   geom_segment(data = norm3.a, aes(yend = y), xend=7, color = "grey50", alpha = 0.25) +

## 직선 위 정규분포를 식별할 수직선을 그린다. 
   geom_vline(xintercept = 2, linetype = 3) + 
   geom_vline(xintercept = 5, linetype = 3) + 
   geom_vline(xintercept = 7, linetype = 3) +

## 수평선 tau를 그린다. 
   geom_hline(yintercept = 2.5, linetype = 2, size = 1, color = "grey30") +

## X축과 Y* 축을 그린다. 
   geom_hline(yintercept = 0, size = 1) +
   geom_vline(yintercept = 0, size = 1) +

## 부가적인 설명 텍스트를 표시한다. 
   annotate("text", x = 8, y = 3, label = "y = 1", size = 10) +
   annotate("text", x = 8, y = 2, label = "y = 0", size = 10) +
   annotate("text", x = -0.7, y = 3, label = "tau = 0", size = 7) +
   annotate("text", x = -0.5, y = 1.0, label = "alpha", size = 7) +
   xlab("X") + ylab("Y*") +
   theme(axis.text=element_text(size=12), axis.title=element_text(size=15,face="bold"))