ggplot2

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ggplot2 Reference

ggplot2 参考文档

ggplot2 is an R package for producing visualizations using a grammar of graphics. You compose plots from data, mappings, layers, scales, facets, coordinates, and themes.
ggplot2是一款基于图形语法的R语言可视化包。你可以通过数据、映射、图层、尺度、分面、坐标系和主题来组合生成图表。

Core Components

核心组件

Data and Mapping

数据与映射

r
ggplot(data = mpg, mapping = aes(x = cty, y = hwy))
  • Data: Tidy data frame (rows = observations, columns = variables)
  • Mapping:
    aes()
    links data columns to visual properties (x, y, colour, size, etc.)
r
ggplot(data = mpg, mapping = aes(x = cty, y = hwy))
  • 数据:整洁的数据框(行=观测值,列=变量)
  • 映射
    aes()
    将数据列关联到视觉属性(x轴、y轴、颜色、大小等)

Layers

图层

Layers display data using geometry, statistical transformation, and position adjustment:
r
ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  geom_smooth(formula = y ~ x, method = "lm")
图层通过几何图形、统计变换和位置调整来展示数据:
r
ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  geom_smooth(formula = y ~ x, method = "lm")

Scales

尺度

Control how data maps to visual properties and create legends/axes:
r
ggplot(mpg, aes(cty, hwy, colour = class)) +
  geom_point() +
  scale_colour_viridis_d()
控制数据如何映射到视觉属性,并生成图例/坐标轴:
r
ggplot(mpg, aes(cty, hwy, colour = class)) +
  geom_point() +
  scale_colour_viridis_d()

Facets

分面

Split data into panels by variables:
r
ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  facet_grid(year ~ drv)
按变量将数据拆分为多个面板:
r
ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  facet_grid(year ~ drv)

Coordinates

坐标系

Interpret position aesthetics (Cartesian, polar, map projections):
r
ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  coord_fixed()
解析位置美学(笛卡尔坐标系、极坐标系、地图投影):
r
ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  coord_fixed()

Theme

主题

Control non-data visual elements:
r
ggplot(mpg, aes(cty, hwy, colour = class)) +
  geom_point() +
  theme_minimal() +
  theme(legend.position = "top")

控制非数据类视觉元素:
r
ggplot(mpg, aes(cty, hwy, colour = class)) +
  geom_point() +
  theme_minimal() +
  theme(legend.position = "top")

ggplot2 4.0 Features

ggplot2 4.0 新特性

ggplot2 4.0.0 (September 2025) introduced S7 classes and major new features.
ggplot2 4.0.0(2025年9月)引入了S7类和多项重要新功能。

S7 Migration

S7 迁移

Access properties with
@
instead of
$
:
r
undefined
使用
@
替代
$
来访问属性:
r
undefined

ggplot2 4.0+

ggplot2 4.0+

ggplot()@data
ggplot()@data

Deprecated (still works temporarily)

已弃用(暂时仍可使用)

ggplot()$data

Stricter type validation:

```r
element_text(hjust = "foo")
#> Error: @hjust must be <NULL>, <integer>, or <double>, not <character>
ggplot()$data

更严格的类型验证:

```r
element_text(hjust = "foo")
#> Error: @hjust must be <NULL>, <integer>, or <double>, not <character>

Theme-Based Layer Defaults

基于主题的图层默认设置

Ink, Paper, and Accent

Ink、Paper与Accent

Built-in themes accept
ink
(foreground),
paper
(background),
accent
(highlight):
r
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  geom_smooth(method = "lm", formula = y ~ x) +
  theme_gray(paper = "cornsilk", ink = "navy", accent = "tomato")
内置主题支持
ink
(前景色)、
paper
(背景色)、
accent
(高亮色)参数:
r
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  geom_smooth(method = "lm", formula = y ~ x) +
  theme_gray(paper = "cornsilk", ink = "navy", accent = "tomato")

element_geom() and from_theme()

element_geom() 与 from_theme()

Set layer defaults via
theme(geom)
:
r
ggplot(mpg, aes(class, displ)) +
  geom_boxplot(aes(colour = from_theme(accent))) +
  theme(geom = element_geom(
    accent = "tomato",
    paper = "cornsilk",
    bordertype = "dashed",
    borderwidth = 0.2,
    linewidth = 2,
    linetype = "solid"
  ))
通过
theme(geom)
设置图层默认值:
r
ggplot(mpg, aes(class, displ)) +
  geom_boxplot(aes(colour = from_theme(accent))) +
  theme(geom = element_geom(
    accent = "tomato",
    paper = "cornsilk",
    bordertype = "dashed",
    borderwidth = 0.2,
    linewidth = 2,
    linetype = "solid"
  ))

Theme Palettes

主题调色板

Set default palettes in themes:
r
theme(
  palette.colour.continuous = c("chartreuse", "forestgreen"),
  palette.shape.discrete = c("triangle", "triangle open")
)
在主题中设置默认调色板:
r
theme(
  palette.colour.continuous = c("chartreuse", "forestgreen"),
  palette.shape.discrete = c("triangle", "triangle open")
)

Theme Shortcuts

主题快捷方式

New
theme_sub_*()
functions reduce verbosity:
ShortcutPrefix replaced
theme_sub_axis()
axis.*
theme_sub_axis_x()
axis.*.x
theme_sub_axis_bottom()
axis.*.x.bottom
theme_sub_legend()
legend.*
theme_sub_panel()
panel.*
theme_sub_plot()
plot.*
theme_sub_strip()
strip.*
r
undefined
新增
theme_sub_*()
系列函数以减少代码冗余:
快捷方式替代的前缀
theme_sub_axis()
axis.*
theme_sub_axis_x()
axis.*.x
theme_sub_axis_bottom()
axis.*.x.bottom
theme_sub_legend()
legend.*
theme_sub_panel()
panel.*
theme_sub_plot()
plot.*
theme_sub_strip()
strip.*
r
undefined

Concise

简洁写法

theme_sub_axis_x( ticks = element_line(colour = "red"), ticks.length = unit(5, "mm") ) + theme_sub_panel( widths = unit(5, "cm"), spacing.x = unit(5, "mm") )
undefined
theme_sub_axis_x( ticks = element_line(colour = "red"), ticks.length = unit(5, "mm") ) + theme_sub_panel( widths = unit(5, "cm"), spacing.x = unit(5, "mm") )
undefined

Margin Helpers

边距辅助函数

r
margin_auto(1)           # all sides = 1
margin_auto(1, 2)        # t/b=1, l/r=2
margin_auto(1, 2, 3)     # t=1, l/r=2, b=3
margin_part(r = 20)      # partial (NA inherits)
r
margin_auto(1)           # 四边均为1
margin_auto(1, 2)        # 上下=1,左右=2
margin_auto(1, 2, 3)     # 上=1,左右=2,下=3
margin_part(r = 20)      # 部分边距(NA表示继承)

Panel Sizes

面板尺寸

r
theme_sub_panel(widths = unit(c(2, 3, 4), "cm"))  # per-panel
theme_sub_panel(widths = unit(9, "cm"))           # total area
r
theme_sub_panel(widths = unit(c(2, 3, 4), "cm"))  # 单个面板尺寸
theme_sub_panel(widths = unit(9, "cm"))           # 总区域尺寸

Labels

标签

Label Attributes

标签属性

Variables with
"label"
attribute auto-populate axis labels:
r
attr(df$bill_dep, "label") <- "Bill depth (mm)"
ggplot(df, aes(bill_dep, bill_len)) + geom_point()
带有
"label"
属性的变量会自动填充坐标轴标签:
r
attr(df$bill_dep, "label") <- "Bill depth (mm)"
ggplot(df, aes(bill_dep, bill_len)) + geom_point()

Dictionary Labels

字典标签

r
dict <- c(species = "Species", bill_dep = "Bill depth (mm)")
ggplot(penguins, aes(bill_dep, bill_len, colour = species)) +
  geom_point() +
  labs(dictionary = dict)
r
dict <- c(species = "Species", bill_dep = "Bill depth (mm)")
ggplot(penguins, aes(bill_dep, bill_len, colour = species)) +
  geom_point() +
  labs(dictionary = dict)

Function Labels

函数式标签

r
scale_colour_discrete(name = toupper)
guides(x = guide_axis(title = tools::toTitleCase))
labs(y = \(x) paste0(x, " variable"))
Label hierarchy (lowest to highest):
aes()
<
labs(dictionary)
< column attribute <
labs()
<
scale_*(name)
<
guide_*(title)
r
scale_colour_discrete(name = toupper)
guides(x = guide_axis(title = tools::toTitleCase))
labs(y = \(x) paste0(x, " variable"))
标签优先级(从低到高):
aes()
<
labs(dictionary)
< 列属性 <
labs()
<
scale_*(name)
<
guide_*(title)

Named Breaks

命名断点

r
scale_colour_discrete(breaks = c(
  "Pygoscelis adeliae" = "Adelie",
  "Pygoscelis papua" = "Gentoo"
))
r
scale_colour_discrete(breaks = c(
  "Pygoscelis adeliae" = "Adelie",
  "Pygoscelis papua" = "Gentoo"
))

Discrete Scale Improvements

离散尺度改进

r
undefined
r
undefined

Palette for spacing

用于间距的调色板

scale_x_discrete(palette = scales::pal_manual(c(1:3, 5:7)))
scale_x_discrete(palette = scales::pal_manual(c(1:3, 5:7)))

Consistent limits across facets

分面间统一的范围

scale_x_discrete(continuous.limits = c(1, 5))
scale_x_discrete(continuous.limits = c(1, 5))

Minor breaks

次要断点

scale_x_discrete( minor_breaks = scales::breaks_width(1, offset = 0.5), guide = guide_axis(minor.ticks = TRUE) )
scale_x_discrete( minor_breaks = scales::breaks_width(1, offset = 0.5), guide = guide_axis(minor.ticks = TRUE) )

Secondary axis

次坐标轴

scale_x_discrete(sec.axis = dup_axis( name = "Counts", breaks = seq_len(7), labels = paste0("n = ", table(mpg$class)) ))
undefined
scale_x_discrete(sec.axis = dup_axis( name = "Counts", breaks = seq_len(7), labels = paste0("n = ", table(mpg$class)) ))
undefined

Position Aesthetics

位置美学

Nudge Aesthetics

偏移美学

r
geom_text(aes(nudge_x = sign(value) * 3, label = value))
r
geom_text(aes(nudge_x = sign(value) * 3, label = value))

Dodge Order

分组顺序

r
ggplot(data, aes(x, y, fill = group)) +
  geom_boxplot(position = position_dodge(preserve = "single")) +
  aes(order = group)
r
ggplot(data, aes(x, y, fill = group)) +
  geom_boxplot(position = position_dodge(preserve = "single")) +
  aes(order = group)

Facets

分面

Wrapping Directions

排列方向

8 direction options for
facet_wrap(dir)
:
dirStartFill
"lt"
top-leftleft-to-right
"tl"
top-lefttop-to-bottom
"lb"
bottom-leftleft-to-right
"bl"
bottom-leftbottom-to-top
"rt"
top-rightright-to-left
"tr"
top-righttop-to-bottom
"rb"
bottom-rightright-to-left
"br"
bottom-rightbottom-to-top
facet_wrap(dir)
支持8种方向选项:
dir起始位置填充方式
"lt"
左上从左到右
"tl"
左上从上到下
"lb"
左下从左到右
"bl"
左下从下到上
"rt"
右上从右到左
"tr"
右上从上到下
"rb"
右下从右到左
"br"
右下从下到上

Free Space

自由空间

r
facet_wrap(~ island, scales = "free_x", space = "free_x")
r
facet_wrap(~ island, scales = "free_x", space = "free_x")

Layer Layout

图层布局

r
geom_point(colour = "grey", layout = "fixed_rows")  # repeat in rows
geom_point(layout = NULL)                            # use facet vars
annotate("text", label = "X", layout = 6)            # specific panel
Options:
NULL
,
"fixed"
,
<integer>
,
"fixed_cols"
,
"fixed_rows"
r
geom_point(colour = "grey", layout = "fixed_rows")  # 在每行重复显示
geom_point(layout = NULL)                            # 使用分面变量
annotate("text", label = "X", layout = 6)            # 指定面板显示
可选值:
NULL
,
"fixed"
,
<integer>
,
"fixed_cols"
,
"fixed_rows"

Styling

样式设置

Boxplot Parts

箱线图部件

r
geom_boxplot(
  whisker.linetype = "dashed",
  box.colour = "black",
  median.linewidth = 2,
  staplewidth = 0.5,
  staple.colour = "grey50"
)
r
geom_boxplot(
  whisker.linetype = "dashed",
  box.colour = "black",
  median.linewidth = 2,
  staplewidth = 0.5,
  staple.colour = "grey50"
)

Violin Quantiles

小提琴图分位数

r
geom_violin(
  quantiles = c(0.1, 0.9),
  quantile.linetype = 1,
  quantile.colour = "red"
)
r
geom_violin(
  quantiles = c(0.1, 0.9),
  quantile.linetype = 1,
  quantile.colour = "red"
)

Labels

标签样式

r
geom_label(
  aes(linetype = factor(vs), linewidth = factor(am)),
  text.colour = "black",
  border.colour = "blue"
)
r
geom_label(
  aes(linetype = factor(vs), linewidth = factor(am)),
  text.colour = "black",
  border.colour = "blue"
)

Varying Fill

渐变填充

r
geom_area(aes(fill = continuous_var))  # gradient (R 4.1+)
r
geom_area(aes(fill = continuous_var))  # 渐变效果(R 4.1+)

New Stats

新统计函数

stat_manual()

stat_manual()

r
make_centroids <- function(df) {
  transform(df, xend = mean(x), yend = mean(y))
}
stat_manual(geom = "segment", fun = make_centroids)
r
make_centroids <- function(df) {
  transform(df, xend = mean(x), yend = mean(y))
}
stat_manual(geom = "segment", fun = make_centroids)

stat_connect()

stat_connect()

r
geom_line(stat = "connect")           # stairstep
geom_ribbon(stat = "connect", alpha = 0.4)
r
geom_line(stat = "connect")           # 阶梯线
geom_ribbon(stat = "connect", alpha = 0.4)

Custom connection shape

自定义连接形状

smooth <- cbind(x = seq(0, 1, length.out = 20)[-1], y = scales::rescale(plogis(x, 0.5, 0.1))) stat_connect(connection = smooth)
undefined
smooth <- cbind(x = seq(0, 1, length.out = 20)[-1], y = scales::rescale(plogis(x, 0.5, 0.1))) stat_connect(connection = smooth)
undefined

Coord Reversal

坐标轴反转

r
coord_cartesian(reverse = "x")   # "y", "xy", "none"
coord_sf(reverse = "y")
coord_radial(reverse = "theta")  # "r", "thetar", "none"
r
coord_cartesian(reverse = "x")   # 可选值:"y", "xy", "none"
coord_sf(reverse = "y")
coord_radial(reverse = "theta")  # 可选值:"r", "thetar", "none"

Deprecations

已弃用功能

OldNew
fatten
median.linewidth
/
middle.linewidth
draw_quantiles
quantiles
geom_errorbarh()
geom_errorbar(orientation = "y")
coord_trans()
coord_transform()
borders()
annotation_borders()
facet_wrap(as.table)
facet_wrap(dir)
theme_get/set/update/replace()
get/set/update/replace_theme()
last_plot()
get_last_plot()
layer_data/grob/scales()
get_layer_data/grob()
,
get_panel_scales()
旧写法新写法
fatten
median.linewidth
/
middle.linewidth
draw_quantiles
quantiles
geom_errorbarh()
geom_errorbar(orientation = "y")
coord_trans()
coord_transform()
borders()
annotation_borders()
facet_wrap(as.table)
facet_wrap(dir)
theme_get/set/update/replace()
get/set/update/replace_theme()
last_plot()
get_last_plot()
layer_data/grob/scales()
get_layer_data/grob()
,
get_panel_scales()