HAHS.
도구와 라이브러리로 돌아가기Back to Tools & Libraries

ggplot2

고수준 코드High-level code

R의 그래픽 문법(grammar of graphics) 패키지로, 현재 4버전이며 테마 수준 기본값과 S7 기반 내부 구조를 갖추고 있습니다R's grammar-of-graphics package for statistical charts, now at version 4 with theme-level defaults and an S7 core

오픈소스Open source windowsmaclinuxr R

현재 버전Current version: 4.0.3, 정보 확인일 2026-10-24facts checked 2026-10-24

개요Overview

ggplot2는 R에서 통계 그래픽을 만드는 표준 패키지입니다. 릴런드 윌킨슨(Leland Wilkinson)의 "그래픽 문법(Grammar of Graphics)"에 기반을 두며, 해들리 위컴(Hadley Wickham)이 시작해 지금은 Posit의 tidyverse 팀이 개발합니다. 차트 유형을 먼저 고르는 대신 데이터, 미학 매핑(aes), 기하 객체(geom), 통계 변환(stat), 스케일, 좌표계, 패싯, 테마를 +로 쌓아 올려 그림을 설명합니다.

ggplot2 is the standard package for statistical graphics in R. It is based on Leland Wilkinson's Grammar of Graphics, was started by Hadley Wickham and is now developed by the tidyverse team at Posit. Instead of picking a chart type first, you describe a plot by stacking data, aesthetic mappings (aes), geoms, stats, scales, a coordinate system, facets and a theme with +.

연구자, 데이터 저널리스트, 대학원생이 논문과 보고서의 그림을 만들 때 가장 많이 쓰는 도구입니다. 같은 문법으로 산점도, 막대 차트, 히스토그램, 상자 그림, 지도까지 만들 수 있어서, 한 번 익히면 새로운 차트를 위해 새 함수를 외울 필요가 줄어듭니다.

Researchers, data journalists and graduate students use it most often for the figures in papers and reports. One grammar covers scatterplots, bar charts, histograms, box plots and maps, so once you know it you rarely need to learn a new function for a new chart.

2025년 9월에 나온 4.0.0은 첫 공개 18주년에 맞춘 대규모 개편이었습니다. 내부 객체 시스템이 S3에서 S7으로 바뀌었고, 레이어 기본값과 팔레트가 테마로 들어갔습니다. 일반 사용자의 코드는 대부분 그대로 동작하지만, 2025년 이전에 쓰인 튜토리얼과 확장 패키지는 4.x에서 한 번 확인해야 합니다.

Version 4.0.0 in September 2025 was a large overhaul timed with the 18th anniversary of the package. The internal object system moved from S3 to S7, and layer defaults and palettes moved into themes. Most everyday code still runs unchanged, but tutorials and extension packages written before 2025 deserve a check against 4.x.

2026년 현재What's new in 2026

  • 최신 버전은 4.0.3(2026-04-22)입니다. 4.0.0은 2025-09-11, 4.0.1은 2025-11-14, 4.0.2는 2026-02-03에 나왔습니다.
  • The current version is 4.0.3 (2026-04-22). Version 4.0.0 came out on 2025-09-11, 4.0.1 on 2025-11-14 and 4.0.2 on 2026-02-03.
  • S3 객체 대부분이 S7로 바뀌었습니다. 인자 타입을 더 엄격히 검사해서 element_text(hjust = "foo") 같은 잘못된 입력이 바로 오류가 되고, 플롯 데이터는 ggplot()@data로도 접근할 수 있습니다. 기존 S3 구조에 기대던 패키지를 위한 호환 장치는 남아 있지만 점차 정리될 예정입니다.
  • Most S3 objects were replaced by S7 objects. Argument types are checked more strictly, so bad input such as element_text(hjust = "foo") fails at once, and plot data is reachable as ggplot()@data. Compatibility shims remain for packages that relied on the S3 structure, and they are expected to be phased out.
  • 레이어 기본값이 테마로 들어왔습니다. theme(geom = element_geom(...))와 from_theme()으로 점 모양, 선 굵기, 색의 기본값을 정하고, 내장 완성 테마에는 ink(전경), paper(배경), accent(강조) 인자가 추가되었습니다.
  • Layer defaults now live in the theme. theme(geom = element_geom(...)) and from_theme() set defaults for point shape, line width and colour, and the built-in complete themes gained ink (foreground), paper (background) and accent arguments.
  • 기본 팔레트도 palette.colour.discrete, palette.colour.continuous, palette.shape.discrete처럼 테마 설정으로 지정할 수 있습니다.
  • Default palettes can also be set from the theme, with settings such as palette.colour.discrete, palette.colour.continuous and palette.shape.discrete.
  • 라벨 처리가 늘었습니다. 열의 label 속성을 축 제목에 쓰고, labs(dictionary = )로 변수명과 라벨 대응표를 한 번에 넘길 수 있습니다.
  • Labelling improved. A column's label attribute is used for axis titles, and labs(dictionary = ) takes a variable-to-label lookup in one step.
  • 테마 코드를 짧게 쓰는 theme_sub_axis_x(), theme_sub_legend(), theme_sub_panel() 같은 함수와 CSS식 margin_auto(), 패널 크기를 직접 정하는 panel.widths와 panel.heights가 추가되었습니다.
  • Shorter theme code is possible with helpers such as theme_sub_axis_x(), theme_sub_legend() and theme_sub_panel(), the CSS-style margin_auto(), and panel.widths and panel.heights to fix panel sizes directly.
  • 이산형 위치 스케일에 palette 인자가 생겨 범주 사이 간격과 묶음을 직접 정할 수 있습니다. geom_violin의 분위수 처리와 히스토그램 구간 경계 등 일부 동작은 바뀌었으므로 예전 그림이 조금 달라질 수 있습니다.
  • Discrete position scales accept a palette argument, so you can control spacing and grouping between categories. Some behaviours changed, including quantile handling in geom_violin and histogram bin boundaries, so older figures can shift slightly.
  • ggplot2 자체에는 AI 기능이 없습니다. 다만 LLM이 가장 자주 만들어 주는 R 코드 중 하나이며, 학습 자료의 상당수가 4.0 이전 문법이므로 생성된 코드는 설치된 버전에서 실제로 돌려 확인해야 합니다.
  • ggplot2 itself has no AI features. It is, however, one of the R libraries LLMs write most often, and much of the training material predates 4.0, so run generated code on your installed version before trusting it.

강점Strengths

  • 하나의 일관된 문법으로 거의 모든 정적 통계 그래픽을 표현합니다.
  • One consistent grammar expresses almost any static statistical graphic.
  • 패싯으로 작은 다중 차트(small multiples)를 한 줄로 만듭니다.
  • Facets turn a plot into small multiples in a single line.
  • 통계 변환(stat)이 내장되어 있어 요약, 평활선, 밀도 추정을 데이터 가공 없이 바로 그립니다.
  • Built-in stats compute summaries, smoothers and density estimates without separate data wrangling.
  • 테마와 기본값 시스템 덕분에 논문이나 조직 양식에 맞는 스타일을 한 번 정의해 재사용합니다.
  • The theme and defaults system lets you define a journal or house style once and reuse it.
  • 코드로 그림을 만들기 때문에 재현 가능하고 버전 관리가 됩니다.
  • Plots are code, so they are reproducible and fit into version control.
  • 확장 패키지가 많아 릿지라인, 네트워크, 애니메이션 같은 기본에 없는 차트를 보완합니다.
  • Many extension packages add charts that are not in the core, such as ridgelines, networks and animation.
  • ggsave()로 PDF, SVG, PNG 같은 출판용 형식을 정확한 크기로 저장합니다.
  • ggsave() writes publication formats such as PDF, SVG and PNG at exact sizes.

한계Limitations

  • R 전용입니다. 팀이 Python 중심이라면 도입 비용이 큽니다.
  • It is R only, which is a real cost if your team works mainly in Python.
  • 기본 출력은 정적 이미지입니다. 상호작용은 변환 패키지나 확장으로 추가해야 하며, 4.x와의 호환은 사용하는 패키지마다 확인해야 합니다.
  • Default output is a static image. Interactivity comes from converter packages or extensions, and compatibility with 4.x has to be checked package by package.
  • 문법을 이해하기 전까지 학습 곡선이 있고, 4.0 이전과 이후의 코드 스타일이 섞여 있어 오래된 예제가 혼란을 줍니다.
  • There is a learning curve until the grammar clicks, and examples from before and after 4.0 are mixed on the web, which confuses beginners.
  • 문법에 없는 그림은 확장 패키지나 직접 만든 stat과 geom이 필요합니다. 네트워크나 3D 그래픽은 기본 범위 밖입니다.
  • Graphics outside the grammar need extension packages or custom stats and geoms. Network and 3D graphics are outside the core scope.
  • 점이 매우 많은 그림은 렌더링이 느려질 수 있어 집계나 geom_hex() 같은 대안을 고려해야 합니다.
  • Plots with very many points can render slowly, so consider aggregation or alternatives such as geom_hex().

이런 용도에 최적Best For

ggplot2는 논문, 학위논문, 보고서에 들어갈 정적 통계 그림에 가장 잘 맞습니다. 그룹별 비교, 분포, 회귀선과 신뢰구간, 패싯 비교처럼 분석과 시각화가 붙어 있는 작업에서 특히 강합니다. R로 분석하는 연구실이나 팀이라면 첫 번째 선택지입니다.

ggplot2 is the best fit for static statistical figures in papers, theses and reports. It is especially strong where analysis and plotting go together: group comparisons, distributions, regression lines with intervals, and faceted comparisons. For a lab or team that analyses in R, it is the first option to consider.

대시보드나 웹에 바로 올릴 상호작용 차트가 목적이라면 Plotly나 Vega-Lite가 더 알맞습니다. 비R 사용자와 같이 편집해야 하는 경우에도 스프레드시트나 BI 도구가 더 쉽습니다.

If the goal is a dashboard or an interactive chart for the web, Plotly or Vega-Lite fits better. When people who do not use R must edit the chart as well, a spreadsheet or BI tool is easier.

시작하기Getting Started

  1. R(4.5 이상이면 penguins 데이터가 기본 포함됩니다)과 RStudio 또는 Positron을 설치합니다.
  2. Install R (version 4.5 or later ships the penguins dataset) and RStudio or Positron.
  3. 콘솔에서 install.packages("ggplot2")를 실행하고 library(ggplot2)로 불러옵니다.
  4. Run install.packages("ggplot2") in the console and load it with library(ggplot2).
  5. 아래 코드를 실행해 데이터, 매핑, geom, 라벨, 테마가 어떻게 이어지는지 확인합니다.
  6. Run the code below and see how data, mappings, geoms, labels and a theme chain together.
  7. ggsave()로 크기를 지정해 파일로 저장합니다.
  8. Save the result with ggsave() at an explicit size.
library(ggplot2)

# penguins ships with base R 4.5 and later (datasets package)
p <- ggplot(penguins, aes(bill_dep, bill_len, colour = species)) +
  geom_point(na.rm = TRUE) +
  geom_smooth(method = "lm", formula = y ~ x, na.rm = TRUE) +
  labs(
    x = "Bill depth (mm)",
    y = "Bill length (mm)",
    colour = "Species",
    title = "Bill length by bill depth in three penguin species"
  ) +
  theme_minimal()

p

ggsave("penguins.png", p, width = 6, height = 4, dpi = 300)

ggplot2 4.x에서 테마로 기본값을 바꾸려면 완성 테마에 ink, paper, accent를 넘기거나 theme(geom = element_geom(...))를 사용합니다.

To change defaults through the theme in ggplot2 4.x, pass ink, paper and accent to a complete theme or use theme(geom = element_geom(...)).

지원 차트 유형Supported Chart Types

ggplot2는 geom 조합으로 막대 차트(geom_col, geom_bar), 누적 막대 차트, 선 그래프, 영역 그래프, 산점도, 버블 차트, 히스토그램, 밀도 곡선, 상자 그림, 바이올린 플롯, 히트맵(geom_tile), 오차 막대, 평활선, 지도(sf 패키지와 geom_sf)를 만듭니다. coord_radial()이나 극좌표 변환으로 도넛과 레이더 형태도 만들 수 있고, 패싯으로 작은 다중 차트를 구성합니다. 릿지라인, 샌키, 네트워크처럼 기본에 없는 차트는 확장 패키지가 필요합니다.

ggplot2 builds bar charts (geom_col, geom_bar), stacked bars, line graphs, area graphs, scatterplots, bubble charts, histograms, density curves, box plots, violin plots, heatmaps (geom_tile), error bars, smoothers and maps (the sf package with geom_sf) from combinations of geoms. Donut and radar-style charts are possible with coord_radial() or polar transforms, and facets produce small multiples. Charts that are not in the core, such as ridgelines, Sankey diagrams and networks, need extension packages.