使用ggplot2和ggtext创建精美的企鹅数据集可视化图表
2025-06-02 04:05:58作者:申梦珏Efrain
本文基于rstudio-conf-2022中关于ggplot2图形设计的研讨会材料,重点讲解如何使用ggplot2和ggtext包创建带有精美注释的企鹅数据集可视化图表。
数据准备
首先我们需要加载并了解数据集。我们使用的是palmerpenguins包提供的企鹅数据集:
library(palmerpenguins)
penguins
这个数据集包含了三种企鹅(阿德利企鹅、帽带企鹅和巴布亚企鹅)的体型测量数据,包括喙长、喙深、鳍状肢长度和体重等信息。
基础图表构建
我们从最基本的散点图开始,展示企鹅喙长和喙深的关系:
ggplot(
penguins,
aes(x = bill_length_mm, y = bill_depth_mm,
color = species, size = body_mass_g)
) +
geom_point(alpha = .2) +
labs(
x = "Bill length (mm)",
y = "Bill depth (mm)",
title = "Bill dimensions of brush-tailed penguins Pygoscelis spec.",
caption = "Horst AM, Hill AP, Gorman KB (2020). palmerpenguins R package version 0.1.0"
)
图表美化步骤
1. 添加点轮廓
为了让数据点更清晰可见,我们添加白色轮廓:
geom_point(alpha = .2, stroke = .3) +
geom_point(shape = 1, stroke = .3)
2. 自定义颜色和大小比例尺
scale_color_manual(
name = "Species:",
values = c("#FF8C00", "#A034F0", "#159090")
) +
scale_size(
name = "Body mass:",
breaks = 3:6 * 1000,
labels = function(x) paste(x / 1000, "kg"),
range = c(.5, 5)
)
3. 调整坐标轴
coord_cartesian(
expand = FALSE,
clip = "off"
) +
scale_x_continuous(
limits = c(30, 60),
breaks = 6:12*5
) +
scale_y_continuous(
limits = c(12.5, 22.5),
breaks = seq(12.5, 22.5, by = 2.5)
使用ggtext增强文本样式
ggtext包允许我们在图表中使用Markdown和HTML标记来格式化文本:
library(ggtext)
labs(
x = "Bill length *(mm)*",
y = "Bill depth *(mm)*",
title = "Bill dimensions of brush-tailed penguins *Pygoscelis spec.*",
caption = "Horst AM, Hill AP, Gorman KB (2020). <span style='font-family:tabular;'>palmerpenguins</span> R package version 0.1.0"
) +
theme(
plot.title = element_markdown(
face = "bold", size = 16, margin = margin(12, 0, 12, 0)
)
添加物种标签注释
我们需要先创建一个包含物种平均数据和格式化标签的数据框:
penguins_labs <-
penguins %>%
group_by(species) %>%
summarize(across(starts_with("bill"), ~ mean(.x, na.rm = TRUE))) %>%
mutate(
species_lab = case_when(
species == "Adelie" ~ "<b style='font-size:15pt;'>*P. adéliae*</b><br>(Adélie penguin)",
species == "Chinstrap" ~ "<b style='font-size:15pt;'>*P. antarctica*</b><br>(Chinstrap penguin)",
species == "Gentoo" ~ "<b style='font-size:15pt;'>*P. papua*</b><br>(Gentoo penguin)"
)
)
然后使用geom_richtext添加注释:
geom_richtext(
data = penguins_labs,
aes(label = species_lab,
color = species,
color = after_scale(colorspace::darken(color, .4))),
family = "Roboto Condensed",
size = 3, lineheight = .8,
fill = "#ffffffab", ## 半透明白色背景
show.legend = FALSE
)
最终主题定制
theme_minimal(
base_size = 10, base_family = "Roboto Condensed"
) +
theme(
plot.title.position = "plot",
plot.caption.position = "plot",
axis.text = element_text(family = "Tabular"),
legend.text = element_text(color = "grey50"),
plot.margin = margin(0, 14, 0, 12),
plot.background = element_rect(fill = NA, color = "grey50", size = 1)
)
总结
通过本教程,我们学习了如何:
- 使用ggplot2创建基础可视化
- 通过多种几何对象增强图表表现力
- 自定义比例尺和坐标轴
- 使用ggtext包实现丰富的文本格式化
- 添加和样式化注释
- 全面定制图表主题
这些技巧可以应用于各种数据可视化场景,帮助你创建既美观又专业的图表。
登录后查看全文
热门项目推荐
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0214
cann-learning-hubCANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。Jupyter Notebook0138
uni-appA cross-platform framework using Vue.jsJavaScript08
GLM-5.2智谱开源 GLM-5.2,这是针对长文本任务的最新旗舰模型。相较于前代产品 GLM-5.1,它在长文本任务处理能力上实现了显著飞跃,并且首次在稳定的 100 万 token 上下文中提供这一能力。Jinja00
SwanLab⚡️SwanLab - an open-source, modern-design AI training tracking and visualization tool. Supports Cloud / Self-hosted use. Integrated with PyTorch / Transformers / LLaMA Factory / veRL/ Swift / Ultralytics / MMEngine / Keras etc.Python00
tiny-universe《大模型白盒子构建指南》:一个全手搓的Tiny-UniverseJupyter Notebook03
项目优选
收起
deepin linux kernel
C
32
16
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
469
465
暂无描述
Dockerfile
778
5.08 K
本项目是CANN提供的transformer类大模型算子库,实现网络在NPU上加速计算。
C++
877
2.03 K
Ascend Extension for PyTorch
Python
758
968
本项目是CANN提供的神经网络类计算算子库,实现网络在NPU上加速计算。
C++
697
1.4 K
昇腾LLM分布式训练框架
Python
185
231
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1.1 K
1.14 K
本仓库是 Flutter SDK 与 Flutter Engine 的 OpenHarmony 适配版本,由 CPF-Flutter 团队维护。开发者可使用熟悉的 Flutter 技术栈开发 OpenHarmony 应用,3.35.7 及以后的适配版本可基于本仓库源码构建支持 OpenHarmony 的 Flutter Engine。
Dart
1.04 K
271
JiuwenSwarm 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。
Python
2.25 K
677