install.packages("ggplot2")
8 ggplot2
통계 그래픽의 문법
R ggplot2
패키지는 통계 그래픽 도구로, 많은 사람들이 사용한다. 심지어 이 패키지를 사용하기 위해서 R 언어를 배울 정도이다.
8.1 참고 자료
- ggplot2: 패키지 저자가 직접 쓴 저서로 기본 개념을 충실히 설명한다.
- Fundamentals of Data Visualization: 이
ggplot2
패키지를 핵심 도구로 삼아, 각종 목적에 맞는 통계 데이터 시각화를 어떻게 할지를 다룬 책이다. 데이터 시각화 교과서: 데이터 분석의 본질을 살리는 그래프와 차트 제작의 기본 원리와 응용라는 책으로 한국에 번역 출판되었다.
8.2 ggplot2 패키지란?
ggplot2
패키지의 gg
는 grammer of graphics
의 약자로, 그래프의 문법을 말한다. 이 패키지는 Wilkinson, Leland 라는 통계학자가 쓴 “The Grammar of Graphics”라는 책에서 소개하는 통계 그래픽의 문법이라는 개념을 R 언어로 구현한 것이다.
이런 개념을 모두 알아야 이 패키지를 쓸 수 있는 것은 아니고, 약간의 개념만 알아도 충분히 사용할 수 있고, 인터넷에는 자료가 넘친다. 위 “Fundamentals of Data Visualization” 책도 정말 훌륭한 책이다.
이 그래픽의 기본 개념에 대해서 알아보자.
ggplot2
은 그래프를 그림 8.3 처럼 나눠서 생각한다.
현재 컴퓨터에 ggplot2
패키지가 설치되어 있지 않다면, 다음과 같이 설치한다.
ggplot2
는 그림 8.3에서 표시한 요소들을 사용하여, 실제 다음과 같은 식으로 플롯을 만든다.
# 데이터 로딩
<- readRDS("./data/stroke_df.rds") stroke_df
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
데이터셋의 hypertension
과 stroke
변수에 대한 막대 그래프이다.
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)
)