이전 글에서 기본 그래프 유형을 다뤘고, 이번에는 밀도 플롯, 히트맵, 패싯, 통계적 요소, 좌표계 설정, 그래프 꾸미기에 대한 내용을 정리합니다.
예제 데이터는 계속 mtcars 데이터셋을 사용합니다.
library(ggplot2)
data(mtcars)
Density Plot: geom_density()
히스토그램의 연속적인 버전입니다.
데이터의 분포를 부드러운 곡선으로 보여줍니다.
ggplot(mtcars, aes(x = mpg)) +
geom_density()
# fill로 채우기
ggplot(mtcars, aes(x = mpg)) +
geom_density(fill = "steelblue", alpha = 0.5)

그룹별로 비교할 때 히스토그램보다 겹쳐서 보기 편합니다.
ggplot(mtcars, aes(x = mpg, fill = factor(cyl))) +
geom_density(alpha = 0.4)

히스토그램과 밀도 곡선을 함께 그리려면 히스토그램의 y축을 밀도 기준으로 바꿔야 합니다.
ggplot(mtcars, aes(x = mpg)) +
geom_histogram(aes(y = after_stat(density)),
binwidth = 3, fill = "gray80", color = "white") +
geom_density(color = "steelblue", linewidth = 1)

after_stat(density)는 히스토그램의 y축을 빈도 수 대신 밀도로 바꾸는 설정입니다.
이전 버전에서는 ..density..를 사용했지만 현재는 after_stat(density)가 권장됩니다.
Heatmap: geom_tile()
두 범주형 변수와 하나의 수치형 변수를 색상으로 표현합니다.
유전자 발현량 히트맵처럼 행렬 데이터를 시각화할 때 자주 사용합니다.
# 예시 데이터: 유전자 발현량
library(tidyverse)
df <- expand.grid(
gene = c("BRCA1", "TP53", "EGFR", "MYC"),
sample = c("s01", "s02", "s03")
)
df$expression <- c(12.5, 8.3, 21.0, 5.1,
11.2, 9.1, 19.8, 4.8,
13.8, 7.6, 22.3, 5.5)
ggplot(df, aes(x = sample, y = gene, fill = expression)) +
geom_tile()

색상 팔레트를 바꾸면 발현량의 높낮이가 더 잘 보입니다.
ggplot(df, aes(x = sample, y = gene, fill = expression)) +
geom_tile(color = "white") +
scale_fill_gradient(low = "white", high = "steelblue")
# 양방향 색상 (낮음-중간-높음)
scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0)
# 내장 팔레트 사용
scale_fill_distiller(palette = "YlOrRd", direction = 1)

Facet: 그래프를 여러 패널로 분할
하나의 그래프를 조건별로 나눠서 여러 패널에 그립니다.
그룹별로 동일한 그래프를 비교할 때 유용합니다.
facet_wrap()
하나의 변수를 기준으로 패널을 나눕니다.
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
facet_wrap(~ cyl)
# 열 수 지정
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
facet_wrap(~ cyl, ncol = 2)
# 축 범위를 패널마다 자유롭게
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
facet_wrap(~ cyl, scales = "free")

- scales = "fixed": 모든 패널이 같은 축 범위 (기본값)
- scales = "free": 패널마다 다른 축 범위
- scales = "free_x", "free_y": x 또는 y만 자유롭게
facet_grid()
두 변수를 기준으로 행과 열로 나눕니다.
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
facet_grid(am ~ cyl)
행 변수 ~ 열 변수 형태로 지정합니다. 한쪽만 변수를 지정하고 싶으면 .을 씁니다.
facet_grid(. ~ cyl) # 열로만 나눔
facet_grid(am ~ .) # 행으로만 나눔
통계적 요소
geom_smooth(): 회귀선/추세선 추가
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth()
# 선형 회귀선
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth(method = "lm", se = TRUE)
# 그룹별 회귀선
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)

- method = "lm": 선형 회귀 (기본값은 "loess")
- se = TRUE: 신뢰구간 표시 (기본값), FALSE로 끄기
- se = FALSE는 신뢰구간 없이 선만 그릴 때
stat_summary(): 그룹별 요약 통계 표시
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
stat_summary(fun = mean, geom = "bar", fill = "steelblue") +
stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.2)

- fun = mean: 평균값을 막대로 표시
- fun.data = mean_se: 평균 ± 표준오차를 에러바로 표시
좌표계 설정
coord_flip(): 축 뒤집기
x축과 y축을 교환합니다. 막대 그래프를 가로 방향으로 바꿀 때 주로 사용합니다.
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
geom_boxplot() +
coord_flip()
coord_polar(): 극좌표계
막대 그래프를 파이 차트로 변환하는 데 사용합니다.
ggplot(mtcars, aes(x = factor(cyl), fill = factor(cyl))) +
geom_bar() +
coord_polar()
scale_x_log10(), scale_y_log10(): 로그 스케일
한쪽으로 치우친 데이터를 보기 좋게 만들 때 사용합니다.
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point() +
scale_x_log10()
# 또는 coord_trans()로 변환
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point() +
coord_trans(x = "log10")
그래프 꾸미기
labs(): 제목과 축 이름 설정
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
labs(
title = "차량 무게와 연비의 관계",
subtitle = "mtcars 데이터셋",
x = "차량 무게 (1000 lbs)",
y = "연비 (mpg)",
caption = "출처: Motor Trend 1974",
color = "실린더 수"
)
scale_color_(), scale_fill_(): 색상 팔레트 설정
# 수동으로 색상 지정
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point() +
scale_color_manual(values = c("4" = "blue", "6" = "green", "8" = "red"))
# 내장 팔레트
scale_color_brewer(palette = "Set1")
scale_fill_brewer(palette = "Pastel1")
# 연속형 변수에 적용
scale_color_gradient(low = "blue", high = "red")
scale_color_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0)
# viridis 팔레트 (색맹 친화적)
scale_color_viridis_d() # d: 이산형
scale_color_viridis_c() # c: 연속형

theme(): 그래프 외양 설정
# 내장 테마
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
theme_bw() # 흰 배경 + 검정 테두리
# theme_minimal() # 최소한의 요소
# theme_classic() # 클래식 스타일
# theme_void() # 배경 없음
theme()으로 세부 요소를 직접 설정할 수 있습니다.
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point() +
labs(title = "예제 그래프") +
theme_bw() +
theme(
plot.title = element_text(size = 14, face = "bold"),
axis.title = element_text(size = 12),
axis.text = element_text(size = 10),
legend.position = "bottom", # 범례 위치
panel.grid.minor = element_blank() # 보조 격자 제거
)

자주 사용하는 theme() 요소입니다.
| 요소 | 의미 |
| plot.title | 그래프 제목 |
| axis.title | 축 이름 |
| axis.text | 축 눈금 텍스트 |
| legend.position | 범례 위치 ("top", "bottom", "left", "right", "none") |
| panel.background | 그래프 배경 |
| panel.grid.major | 주요 격자선 |
| panel.grid.minor | 보조 격자선 |
| strip.text | facet 패널 제목 텍스트 |
그래프 저장: ggsave()
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
ggsave("plot.png", plot = p, width = 8, height = 5, dpi = 300)
ggsave("plot.pdf", plot = p, width = 8, height = 5)
dpi = 300은 논문이나 보고서용 해상도입니다.
'BI&Programming-Tools > R' 카테고리의 다른 글
| [R 기초] 10. ggplot2 시각화 기초 (0) | 2026.06.30 |
|---|---|
| [R 기초] 9. Tidyverse (0) | 2026.06.29 |
| [R 기초] 8. 데이터 전처리 (0) | 2026.06.29 |
| [R 기초] 7. 제어문과 함수 (0) | 2026.06.29 |
| [R 기초] 6. 데이터 구조 (행렬, 데이터프레임) (0) | 2026.06.28 |
