8  ggplot2 통계 그래픽의 문법

R ggplot2 패키지는 통계 그래픽 도구로, 많은 사람들이 사용한다. 심지어 이 패키지를 사용하기 위해서 R 언어를 배울 정도이다.

8.1 참고 자료

  • ggplot2: 패키지 저자가 직접 쓴 저서로 기본 개념을 충실히 설명한다.
그림 8.1: ggplot2
그림 8.2: Fundamentals of Data Visualization

8.2 ggplot2 패키지란?

ggplot2 패키지의 gggrammer of graphics의 약자로, 그래프의 문법을 말한다. 이 패키지는 Wilkinson, Leland 라는 통계학자가 쓴 “The Grammar of Graphics”라는 책에서 소개하는 통계 그래픽의 문법이라는 개념을 R 언어로 구현한 것이다.

이런 개념을 모두 알아야 이 패키지를 쓸 수 있는 것은 아니고, 약간의 개념만 알아도 충분히 사용할 수 있고, 인터넷에는 자료가 넘친다. 위 “Fundamentals of Data Visualization” 책도 정말 훌륭한 책이다.

이 그래픽의 기본 개념에 대해서 알아보자.

그림 8.3: ggplot2에서 다루는 플롯의 구성 요소(Introduction to ggplot2 비니에트에서 인용)

ggplot2은 그래프를 그림 8.3 처럼 나눠서 생각한다.

현재 컴퓨터에 ggplot2 패키지가 설치되어 있지 않다면, 다음과 같이 설치한다.

install.packages("ggplot2")

ggplot2그림 8.3에서 표시한 요소들을 사용하여, 실제 다음과 같은 식으로 플롯을 만든다.

# 데이터 로딩 
stroke_df <- readRDS("./data/stroke_df.rds")
library(ggplot2)
ggplot(stroke_df) + 
    geom_density(aes(avg_glucose_level, fill=stroke)) + 
    theme_bw() + 
    labs(title = "Density Plot of Average Glucose Level By Stroke",
         x = "Average Glucose Level",
         y = "Density") +
    theme(
        plot.title = element_text(size = 15, face = "bold", color="steelblue"),
        axis.text = element_text(size = 12),
        axis.title = element_text(size = 15), 
        legend.text = element_text(size=12),
        legend.title = element_text(size=15)
    )

다음은 stroke_df 데이터셋의 hypertensionstroke 변수에 대한 막대 그래프이다.

ggplot(stroke_df) +
    geom_bar(aes(hypertension, fill=stroke)) +
    labs(title = "Bar Plot of Hypertension By Stroke",
         x = "Hypertension",
         y = "Count") +
    theme_bw() + 
    theme(
        plot.title = element_text(size = 15, face = "bold", color="steelblue"),
        axis.text = element_text(size = 12),
        axis.title = element_text(size = 15), 
        legend.text = element_text(size=12),
        legend.title = element_text(size=15)
    )

비율(proportion)으로 시각화하면 고혈압이 있는 그룹에서 뇌졸중 발생 비율이 더 높다는 것을 알 수 있다.

ggplot(stroke_df) +
    geom_bar(aes(hypertension, fill=stroke), position = "fill") +
    scale_y_continuous(labels = scales::percent_format()) +
    labs(title = "Proportion of Hypertension By Stroke",
         x = "Hypertension",
         y = "Proportion") +
    theme_bw() + 
    theme(
        plot.title = element_text(size = 15, face = "bold", color="steelblue"),
        axis.text = element_text(size = 12),
        axis.title = element_text(size = 15), 
        legend.text = element_text(size=12),
        legend.title = element_text(size=15)
    )