关于 ggplot2
ggplot2 是用于构建可视化的 R 程序包,可组合数据映射、图层、尺度、分面、坐标和主题。此参考资料介绍其绘图模型及部分 ggplot2 4.0 功能,适合创建和设置图表样式的 R 用户。
主要功能
- 01组合数据与美学映射构建图表
- 02添加几何图层和统计图层
- 03配置尺度、图例与坐标轴
- 04按变量拆分为分面面板
- 05调整主题、标签和坐标
- 06使用 ggplot2 4.0 主题与统计功能
适用场景
- 01绘制带拟合趋势的散点图
- 02通过分面面板比较不同组
- 03自定义图表配色、标签和布局
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jsperger/ llm-r-skills --skill ggplot2安装后在 Claude Code 中输入/ggplot2确认已加载。
详细介绍
ggplot2 参考
ggplot2 是一个使用图形语法生成可视化的 R 软件包。你可以通过数据、映射、图层、刻度、分面、坐标和主题组合绘图。
核心组件
数据和映射
ggplot(data = mpg, mapping = aes(x = cty, y = hwy))
- 数据:整洁数据框(行 = 观测值,列 = 变量)
- 映射:
aes()将数据列关联到视觉属性(x、y、颜色、大小等)
图层
图层使用几何对象、统计变换和位置调整来显示数据:
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
geom_smooth(formula = y ~ x, method = "lm")
刻度
控制数据如何映射到视觉属性,并创建图例/坐标轴:
ggplot(mpg, aes(cty, hwy, colour = class)) +
geom_point() +
scale_colour_viridis_d()
分面
按变量将数据拆分到多个面板中:
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
facet_grid(year ~ drv)
坐标
解读位置美学属性(笛卡尔坐标、极坐标、地图投影):
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
coord_fixed()
主题
控制与数据无关的视觉元素:
ggplot(mpg, aes(cty, hwy, colour = class)) +
geom_point() +
theme_minimal() +
theme(legend.position = "top")
ggplot2 4.0 特性
ggplot2 4.0.0(2025 年 9 月)引入了 S7 类和多项重要新特性。
S7 迁移
使用 @ 而不是 $ 访问属性:
# ggplot2 4.0+
ggplot()@data
# Deprecated (still works temporarily)
ggplot()$data
更严格的类型验证:
element_text(hjust = "foo")
#> Error: @hjust must be <NULL>, <integer>, or <double>, not <character>
基于主题的图层默认值
墨色、纸色和强调色
内置主题支持 ink(前景色)、paper(背景色)和 accent(强调色):
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ x) +
theme_gray(paper = "cornsilk", ink = "navy", accent = "tomato")
element_geom() 和 from_theme()
通过 theme(geom) 设置图层默认值:
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(
palette.colour.continuous = c("chartreuse", "forestgreen"),
palette.shape.discrete = c("triangle", "triangle open")
)
主题快捷方式
新的 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.* |
# 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")
)
边距辅助函数
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)
面板大小
theme_sub_panel(widths = unit(c(2, 3, 4), "cm")) # per-panel
theme_sub_panel(widths = unit(9, "cm")) # total area
标签
标签属性
带有 "label" 属性的变量会自动填充坐标轴标签:
attr(df$bill_dep, "label") <- "Bill depth (mm)"
ggplot(df, aes(bill_dep, bill_len)) + geom_point()
字典标签
dict <- c(species = "Species", bill_dep = "Bill depth (mm)")
ggplot(penguins, aes(bill_dep, bill_len, colour = species)) +
geom_point() +
labs(dictionary = dict)
函数标签
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)
命名中断点
scale_colour_discrete(breaks = c(
"Pygoscelis adeliae" = "Adelie",
"Pygoscelis papua" = "Gentoo"
))
离散刻度改进
# Palette for spacing
scale_x_discrete(palette = scales::pal_manual(c(1:3, 5:7)))
# Consistent limits across facets
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)
)
# Secondary axis
scale_x_discrete(sec.axis = dup_axis(
name = "Counts",
breaks = seq_len(7),
labels = paste0("n = ", table(mpg$class))
))
位置美学属性
微调美学属性
geom_text(aes(nudge_x = sign(value) * 3, label = value))
避让顺序
ggplot(data, aes(x, y, fill = group)) +
geom_boxplot(position = position_dodge(preserve = "single")) +
aes(order = group)
分面
换行方向
facet_wrap(dir) 有 8 种方向选项:
| dir | 起始位置 | 填充方向 |
|---|---|---|
"lt" | 左上 | 从左到右 |
"tl" | 左上 | 从上到下 |
"lb" | 左下 | 从左到右 |
"bl" | 左下 | 从下到上 |
"rt" | 右上 | 从右到左 |
"tr" | 右上 | 从上到下 |
"rb" | 右下 | 从右到左 |
"br" | 右下 | 从下到上 |
自由空间
facet_wrap(~ island, scales = "free_x", space = "free_x")
图层布局
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
选项:NULL、"fixed"、<integer>、"fixed_cols"、"fixed_rows"
样式设置
箱线图部分
geom_boxplot(
whisker.linetype = "dashed",
box.colour = "black",
median.linewidth = 2,
staplewidth = 0.5,
staple.colour = "grey50"
)
小提琴图分位数
geom_violin(
quantiles = c(0.1, 0.9),
quantile.linetype = 1,
quantile.colour = "red"
)
标签
geom_label(
aes(linetype = factor(vs), linewidth = factor(am)),
text.colour = "black",
border.colour = "blue"
)
变化填充
geom_area(aes(fill = continuous_var)) # gradient (R 4.1+)
新统计方法
stat_manual()
make_centroids <- function(df) {
transform(df, xend = mean(x), yend = mean(y))
}
stat_manual(geom = "segment", fun = make_centroids)
stat_connect()
geom_line(stat = "connect") # stairstep
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)
坐标反转
coord_cartesian(reverse = "x") # "y", "xy", "none"
coord_sf(reverse = "y")
coord_radial(reverse = "theta") # "r", "thetar", "none"
弃用项
| 旧项 | 新项 |
|---|---|
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() |
评论
支持 Markdown