iBetter Books
수정

Ch 06. 차트 저장과 재사용

차트를 만들었다면 다음 단계는 재사용입니다. 보고서에 삽입할 이미지로 저장하거나, 여러 차트를 한 페이지에 배치하거나, 공통 설정을 가진 차트 객체를 변수에 담아두는 방법이 있습니다.

차트를 변수에 저장

ggplot2의 차트는 R 객체입니다. 변수에 담아두었다가 나중에 출력하거나 수정할 수 있습니다.

library(tidyverse)

# 차트를 변수에 저장
p_scatter <- ggplot(mpg, aes(x = displ, y = hwy, color = class)) +
  geom_point(size = 2, alpha = 0.7) +
  labs(
    title = "배기량과 고속도로 연비",
    x     = "배기량 (리터)",
    y     = "연비 (mpg)",
    color = "클래스"
  ) +
  theme_minimal()

# 출력
p_scatter

p_scatter를 실행하면 차트가 그려집니다.

변수에 저장해두면 나중에 레이어를 추가할 수도 있습니다.

# 저장된 차트에 추세선 추가
p_scatter + geom_smooth(method = "lm", se = FALSE, color = "black")

원본 p_scatter는 변경되지 않습니다. +로 레이어를 더한 새로운 차트가 만들어질 뿐입니다.

ggsave로 파일 저장

ggsave()는 ggplot2 차트를 이미지 파일로 저장합니다.

# 현재 화면에 출력된 차트를 저장
ggsave("scatter_plot.png")

기본적으로 마지막으로 출력된 차트를 저장합니다. 특정 차트를 저장하려면 plot 인수를 씁니다.

ggsave(
  filename = "scatter_plot.png",
  plot     = p_scatter,
  width    = 8,
  height   = 6,
  dpi      = 300
)
인수 설명 기본값
filename 저장할 파일 경로와 이름 필수
plot 저장할 차트 객체 마지막 출력 차트
width 너비 (단위: inches) 7
height 높이 (단위: inches) 5
dpi 해상도 (dots per inch) 300
units 크기 단위 ("in", "cm", "mm", "px") "in"
bg 배경색 "white"

파일 형식

파일 이름의 확장자로 형식이 결정됩니다.

형식 확장자 특징
PNG .png 웹, 문서 삽입용 (권장)
JPEG .jpg 사진형 이미지, 용량 작음
PDF .pdf 벡터, 확대해도 선명
SVG .svg 벡터, 웹 친화적
TIFF .tiff 고품질 인쇄용

발표 자료에는 PNG, 논문에는 PDF나 TIFF를 씁니다.

해상도와 크기 설정 가이드

용도 권장 설정
웹/화면 dpi = 96, width = 8, height = 6
발표 자료 dpi = 150, width = 10, height = 7
인쇄/보고서 dpi = 300, width = 8, height = 6
학술 논문 dpi = 600, width = 6, height = 4
# 보고서용 고해상도 저장
ggsave(
  filename = "report_scatter.png",
  plot     = p_scatter,
  width    = 8,
  height   = 6,
  dpi      = 300,
  bg       = "white"
)

bg = "white"는 배경을 흰색으로 지정합니다. 테마에 따라 배경이 투명해질 수 있어서, 문서 삽입용으로 저장할 때는 명시하는 것이 좋습니다.

patchwork — 여러 차트 조합

여러 차트를 나란히 배치하거나 위아래로 쌓고 싶을 때는 patchwork 패키지를 씁니다.

install.packages("patchwork")
library(patchwork)

먼저 차트를 여러 개 만들어 변수에 저장합니다.

# 차트 1: 산점도
p1 <- ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point(color = "steelblue", alpha = 0.6) +
  labs(title = "배기량과 연비", x = "배기량 (리터)", y = "연비 (mpg)") +
  theme_minimal()

# 차트 2: 막대그래프
p2 <- ggplot(mpg, aes(x = class, fill = class)) +
  geom_bar() +
  labs(title = "클래스별 대수", x = "클래스", y = "대수") +
  theme_minimal() +
  theme(legend.position = "none",
        axis.text.x = element_text(angle = 45, hjust = 1))

# 차트 3: 박스플롯
p3 <- ggplot(mpg, aes(x = drv, y = hwy, fill = drv)) +
  geom_boxplot(alpha = 0.7) +
  labs(title = "구동 방식별 연비 분포", x = "구동 방식", y = "연비 (mpg)") +
  theme_minimal() +
  theme(legend.position = "none")

# 차트 4: 히스토그램
p4 <- ggplot(mpg, aes(x = hwy)) +
  geom_histogram(bins = 20, fill = "steelblue", color = "white") +
  labs(title = "연비 분포", x = "고속도로 연비 (mpg)", y = "빈도") +
  theme_minimal()

나란히 배치 — | 연산자

p1 | p2

|로 연결하면 좌우로 나란히 배치됩니다.

위아래 배치 — / 연산자

p1 / p2

/로 연결하면 위아래로 쌓입니다.

복합 배치

# 위에 p1, 아래에 p2와 p3를 나란히
p1 / (p2 | p3)
# 2×2 격자
(p1 | p2) / (p3 | p4)
# 3열로 배치
p1 | p2 | p3

공통 제목과 레이블 붙이기

combined <- (p1 | p2) / (p3 | p4) +
  plot_annotation(
    title    = "mpg 데이터 종합 분석",
    subtitle = "ggplot2 내장 데이터셋 활용",
    caption  = "출처: ggplot2 mpg 데이터셋",
    theme    = theme(
      plot.title    = element_text(size = 16, face = "bold"),
      plot.subtitle = element_text(size = 11, color = "gray40")
    )
  )

combined

plot_annotation()으로 조합된 차트 전체의 제목과 설명을 붙입니다.

patchwork 차트 저장

patchwork로 조합한 차트도 ggsave()로 저장합니다.

ggsave(
  filename = "combined_charts.png",
  plot     = combined,
  width    = 14,
  height   = 10,
  dpi      = 300,
  bg       = "white"
)

여러 패널을 담으므로 너비와 높이를 넉넉하게 지정합니다.

패널 크기 조정

plot_layout()으로 각 패널의 상대적 크기를 지정합니다.

# p1을 p2보다 2배 넓게
p1 | p2 + plot_layout(widths = c(2, 1))
# 위 패널을 아래보다 2배 높게
p1 / p2 + plot_layout(heights = c(2, 1))
# 복합 배치에서 열 비율 지정
(p1 | p2 | p3) + plot_layout(widths = c(2, 1, 1))

전체 워크플로우 정리

PART 04에서 배운 내용을 하나의 흐름으로 정리합니다.

library(tidyverse)
library(patchwork)

# 1. 데이터 준비
mpg_summary <- mpg |>
  group_by(class) |>
  summarise(
    count    = n(),
    mean_hwy = mean(hwy),
    .groups  = "drop"
  )

# 2. 차트 작성 — 변수에 저장
p_bar <- ggplot(mpg_summary, aes(x = fct_reorder(class, mean_hwy),
                                  y = mean_hwy,
                                  fill = class)) +
  geom_col(alpha = 0.8) +
  scale_fill_brewer(palette = "Set2") +
  coord_flip() +
  labs(title = "클래스별 평균 연비", x = NULL, y = "평균 연비 (mpg)") +
  theme_minimal() +
  theme(legend.position = "none")

p_scatter <- ggplot(mpg, aes(x = displ, y = hwy, color = class)) +
  geom_point(alpha = 0.6, size = 2) +
  geom_smooth(method = "lm", se = FALSE, color = "gray30",
              linewidth = 0.5, linetype = "dashed") +
  scale_color_brewer(palette = "Set2") +
  labs(title = "배기량과 연비 관계", x = "배기량 (리터)",
       y = "연비 (mpg)", color = "클래스") +
  theme_minimal()

# 3. 조합
final_plot <- p_bar | p_scatter +
  plot_annotation(
    title   = "자동차 연비 분석 대시보드",
    caption = "출처: ggplot2 mpg 데이터셋"
  )

# 4. 저장
ggsave(
  filename = "mpg_dashboard.png",
  plot     = final_plot,
  width    = 14,
  height   = 6,
  dpi      = 300,
  bg       = "white"
)

차트를 변수에 저장하고, patchwork로 조합하고, ggsave로 내보내는 패턴입니다. 보고서나 발표 자료를 만들 때 이 흐름을 반복하게 됩니다.

PART 04에서는 ggplot2의 레이어 철학부터 시작해 기본 차트, 분포 시각화, 색상과 테마, facet, 저장과 조합까지 전 과정을 다뤘습니다. 다음 파트에서는 공공 데이터를 직접 분석하는 프로젝트로 넘어갑니다.