R ggplot2 快速上手:可靠图表的高效配方
问题
在紧迫的截止日期下,分析人员很难稳定产出风格一致的 R 图表。在缺乏统一模板的情况下频繁切换 geoms、scales 和 themes,往往会得到嘈杂的可视化,并且需要反复返工修修补补。
激化
映射位置错误、图例缺失、颜色比例不一致,会生成误导决策者的图表。时间被浪费在不断微调默认设置上,而不是聚焦于数据中的关键信号。
解决方案
使用一小套紧凑的 ggplot2 图表配方,始终显式指定美学映射,将映射与固定设置分离,并统一应用简洁的主题。下面的模式涵盖了最常用的图表类型,以及如何通过分面进行对比分析。
散点:关系与趋势线
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3, alpha = 0.8) +
geom_smooth(method = "lm", se = FALSE, linewidth = 0.8) +
labs(color = "Cylinders", x = "Weight", y = "MPG") +
theme_minimal()折线:时间序列或有序类别
ggplot(economics, aes(x = date, y = unemploy)) +
geom_line(color = "#1f77b4", linewidth = 1) +
labs(x = "Date", y = "Unemployment") +
scale_x_date(date_breaks = "2 years", date_labels = "%Y") +
theme_minimal()柱状:计数或总量
ggplot(diamonds, aes(x = cut, fill = cut)) +
geom_bar(width = 0.7, color = "white") +
labs(x = "Cut", y = "Count") +
theme_minimal() +
theme(legend.position = "none")箱线与小提琴:分布对比
ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) +
geom_violin(alpha = 0.4, color = NA) +
geom_boxplot(width = 0.18, outlier.shape = NA, alpha = 0.8) +
labs(x = NULL, y = "Sepal Length") +
theme_minimal() +
theme(legend.position = "none")分面:快速对比
ggplot(diamonds, aes(carat, price, color = cut)) +
geom_point(alpha = 0.4, size = 1.5) +
facet_wrap(~ color) +
labs(x = "Carat", y = "Price") +
theme_light()Geoms 与最佳使用场景
| Geom | 数据类型 | 最适合 | 小提示 |
|---|---|---|---|
geom_point() | 数值 vs 数值 | 关系、聚类 | 将颜色/形状映射到类别;配合 geom_smooth() 查看趋势。 |
geom_line() | 有序 x、数值 y | 时间序列、序列数据 | 使用 group= 保持每组一条线;避免排序错误。 |
geom_bar()(计数) / geom_col()(已汇总) | 分类型 | 频数或总量 | 使用 position = "fill" 展示百分比。 |
geom_boxplot() | 分类型 vs 数值 | 对比中位数 / 四分位距 | 搭配 coord_flip() 解决标签过长问题。 |
geom_violin() | 分类型 vs 数值 | 分布形状 | 与箱线图结合以展示分位数。 |
geom_histogram() | 单个数值变量 | 分布 | 显式设置 bins 或 binwidth。 |
映射 vs 固定设置
- 数据映射写在
aes()内:aes(color = species)。 - 固定常量写在
aes()外:geom_point(color = "steelblue")。 - 使用
scale_*函数格式化数值、控制调色板。
主题与标注清单
- 以
theme_minimal()或theme_light()作为简洁的默认样式起点。 - 使用
labs(title, subtitle, caption)提供上下文说明;坐标轴文字保持简短。 - 当颜色已经与分面或标签重复时,用
theme(legend.position = "none")隐藏多余图例。 - 用于发表时,通过
theme(text = element_text(size = 12))调整整体字体大小。
起步模板
base_plot <- ggplot(data, aes(x = x_var, y = y_var)) +
geom_point(color = "#4e79a7", alpha = 0.7) +
labs(
title = "Headline metric",
x = "X axis",
y = "Y axis",
caption = "Source: internal data"
) +
theme_minimal()相关指南
- 绘图前先清洗数据:R dplyr Data Wrangling Pipeline
- 热力图专用选项: pheatmap in R
- 快速创建基础表: How to Create a Dataframe in R