ggplot2 핵심
Shiny 앱에서 가장 자주 보이는 것이 그래프입니다. ggplot2는 R에서 가장 널리 쓰이는 시각화 패키지로, 레이어를 쌓아가며 그래프를 만드는 방식으로 동작합니다.
library(ggplot2)
# 또는
library(tidyverse) # ggplot2 포함
레이어 개념
ggplot2의 핵심 개념은 "레이어를 쌓는다"는 것입니다. 그림을 그리는 것처럼 캔버스(ggplot)를 만들고, 그 위에 점, 선, 막대 등을 올립니다.
ggplot(data = 데이터프레임) + # 1. 캔버스 설정
aes(x = x열, y = y열) + # 2. 데이터 매핑
geom_point() # 3. 기하 도형(점) 추가
+ 기호로 레이어를 추가합니다. 파이프(|>)가 아닌 +를 사용한다는 점을 기억하세요.
aes() — 미적 요소 매핑
aes()는 데이터의 어떤 열을 시각적 속성(x축, y축, 색상, 크기 등)에 연결할지 정합니다.
# 기본 매핑
aes(x = score, y = year)
# 색상과 크기도 데이터로 결정
aes(x = score, y = year, color = dept, size = score)
color, fill, size, shape, alpha 등이 자주 사용하는 미적 속성입니다.
geom_* — 기하 도형
geom_* 함수가 실제로 그래프 위에 무언가를 그립니다.
# 실습 데이터
df <- data.frame(
x = c(1, 2, 3, 4, 5),
y = c(3, 7, 5, 9, 6),
group = c("A", "B", "A", "B", "A")
)
산점도
ggplot(df, aes(x = x, y = y)) +
geom_point(size = 3, color = "steelblue")
선 그래프
ggplot(df, aes(x = x, y = y)) +
geom_line(color = "steelblue") +
geom_point(size = 3) # 점도 함께 추가
막대 그래프
ggplot(df, aes(x = group, fill = group)) +
geom_bar() # 각 그룹의 빈도를 자동 계산
# 미리 계산된 값으로 막대 높이 지정
ggplot(df, aes(x = group, y = y)) +
geom_col(fill = "steelblue")
히스토그램
set.seed(42)
data <- data.frame(value = rnorm(500, mean = 50, sd = 10))
ggplot(data, aes(x = value)) +
geom_histogram(bins = 30, fill = "steelblue", color = "white")
박스플롯
ggplot(df, aes(x = group, y = y, fill = group)) +
geom_boxplot()
theme — 스타일 조정
그래프의 배경, 글꼴, 축 등 시각적 스타일을 변경합니다.
ggplot(df, aes(x = x, y = y)) +
geom_point() +
theme_minimal() # 미니멀 스타일
자주 사용하는 기본 테마입니다.
| 함수 | 스타일 |
|---|---|
theme_gray() |
회색 배경 (기본값) |
theme_minimal() |
깔끔한 흰 배경 |
theme_classic() |
클래식한 축 선 스타일 |
theme_bw() |
흰 배경, 검정 테두리 |
theme_void() |
축 없음 (지도 등에 활용) |
세부 요소는 theme()으로 직접 조정합니다.
ggplot(df, aes(x = x, y = y)) +
geom_point() +
theme_minimal() +
theme(
plot.title = element_text(size = 16, face = "bold"),
axis.title = element_text(size = 12),
legend.position = "bottom"
) +
labs(
title = "점수 분포",
x = "X 값",
y = "Y 값"
)
Shiny에서 ggplot2 사용하기
Shiny에서는 renderPlot() 안에 ggplot2 코드를 넣습니다.
server <- function(input, output, session) {
output$plot <- renderPlot({
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3) +
theme_minimal() +
labs(
title = "연비와 차 무게의 관계",
x = "무게 (1000 lbs)",
y = "연비 (mpg)",
color = "실린더 수"
)
})
}
사용자 입력에 따라 그래프를 바꾸는 패턴을 PART 04에서 자세히 다룹니다.
빠른 참고 — 자주 쓰는 조합
# 그룹별 색상 구분 산점도
ggplot(data, aes(x = x, y = y, color = group)) +
geom_point() +
theme_minimal()
# 그룹별 막대 그래프 (나란히)
ggplot(data, aes(x = category, y = value, fill = group)) +
geom_col(position = "dodge") +
theme_minimal()
# 그룹별 히스토그램 (겹치기)
ggplot(data, aes(x = value, fill = group)) +
geom_histogram(alpha = 0.5, position = "identity") +
theme_minimal()