R ggplot2 퀵스타트: 신뢰할 수 있는 차트를 빠르게 만드는 레시피
Problem
분석가는 촉박한 마감 속에서 일관된 R 차트를 만들기 어려워합니다. 미리 정해진 템플릿 없이 geoms, scales, themes를 오가다 보면, 시각화가 지저분해지고 같은 수정을 반복하게 됩니다.
Agitate
잘못 배치된 aesthetics, 누락된 legend, 맞지 않는 color scale 때문에 이해관계자가 오해하기 쉬운 차트가 만들어집니다. 신호에 집중하기보다 기본 설정을 수정하는 데 시간을 낭비하게 됩니다.
Solution
명시적인 aesthetics, 매핑과 고정 설정의 분리, 깔끔한 theme를 유지하는 소규모 ggplot2 레시피 세트를 사용하세요. 아래 패턴은 가장 자주 요구되는 플롯 유형과, 비교를 위한 facet 사용법을 다룹니다.
Scatter: 관계와 추세선
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3, alpha = 0.8) +
geom_smooth(method = "lm", se = FALSE, linewidth = 0.8) +
labs(color = "Cylinders", x = "Weight", y = "MPG") +
theme_minimal()Line: 시계열 또는 순서가 있는 범주
ggplot(economics, aes(x = date, y = unemploy)) +
geom_line(color = "#1f77b4", linewidth = 1) +
labs(x = "Date", y = "Unemployment") +
scale_x_date(date_breaks = "2 years", date_labels = "%Y") +
theme_minimal()Bar: 개수 또는 합계
ggplot(diamonds, aes(x = cut, fill = cut)) +
geom_bar(width = 0.7, color = "white") +
labs(x = "Cut", y = "Count") +
theme_minimal() +
theme(legend.position = "none")Box and violin: 분포 비교
ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) +
geom_violin(alpha = 0.4, color = NA) +
geom_boxplot(width = 0.18, outlier.shape = NA, alpha = 0.8) +
labs(x = NULL, y = "Sepal Length") +
theme_minimal() +
theme(legend.position = "none")Facets: 빠른 비교
ggplot(diamonds, aes(carat, price, color = cut)) +
geom_point(alpha = 0.4, size = 1.5) +
facet_wrap(~ color) +
labs(x = "Carat", y = "Price") +
theme_light()Geoms와 추천 사용 사례
| Geom | Data type | Best for | Tip |
|---|---|---|---|
geom_point() | numeric vs numeric | 관계, 클러스터 | 색/shape를 범주에 매핑하고, 추세를 위해 geom_smooth()를 추가하세요. |
geom_line() | ordered x, numeric y | 시계열, 순차 데이터 | group=으로 그룹당 하나의 선을 유지하고, 정렬 오류를 피하세요. |
geom_bar() (count) / geom_col() (pre-agg) | categorical | 개수 또는 합계 | 비율은 position = "fill"을 사용하세요. |
geom_boxplot() | categorical vs numeric | 중앙값/IQR 비교 | 라벨이 길면 coord_flip()과 함께 사용하세요. |
geom_violin() | categorical vs numeric | 분포 모양 | 사분위를 보여주기 위해 boxplot과 함께 사용하세요. |
geom_histogram() | single numeric | 분포 | bins 또는 binwidth를 명시적으로 지정하세요. |
Aesthetics vs. 고정 설정
- 데이터 매핑은
aes()안에:aes(color = species). - 고정 값은
aes()밖에서 설정:geom_point(color = "steelblue"). - 값 포맷과 팔레트 제어에는
scale_*함수를 사용하세요.
Theme와 라벨링 체크리스트
- 깔끔한 기본값을 위해
theme_minimal()또는theme_light()로 시작하세요. - 맥락을 위해
labs(title, subtitle, caption)을 추가하고, 축 라벨은 짧게 유지하세요. - 색이 facet 또는 라벨과 중복될 때는
theme(legend.position = "none")으로 불필요한 legend를 숨기세요. - 출판용이라면
theme(text = element_text(size = 12))로 글꼴 크기를 조정하세요.
Starter template
base_plot <- ggplot(data, aes(x = x_var, y = y_var)) +
geom_point(color = "#4e79a7", alpha = 0.7) +
labs(
title = "Headline metric",
x = "X axis",
y = "Y axis",
caption = "Source: internal data"
) +
theme_minimal()Related guides
- 시각화 전에 데이터 정리: R dplyr Data Wrangling Pipeline
- heatmap 전용 옵션: pheatmap in R
- base 테이블을 빠르게 만들기: How to Create a Dataframe in R