05主题与调色板扩展

使用 ggthemes 与 ggthemr 统一图形外观,并分清局部主题图层和全局主题状态。

2026-03-05
Rggplot2ggthemesggthemrThemesPalettes
本章目录 · 6

ggplot2 的主题控制背景、网格、字体、图例和坐标轴等非数据元素;颜色标度控制数据值如何映射到颜色。扩展包可以快速提供一套完整风格,但主题与配色仍是两个不同层次。

从一张基础图开始

library(ggplot2)

mtcars2 <- within(mtcars, {
  vs <- factor(vs, labels = c("V-shaped", "Straight"))
  am <- factor(am, labels = c("Automatic", "Manual"))
  cyl <- factor(cyl)
  gear <- factor(gear)
})

p <- ggplot(mtcars2, aes(wt, mpg, color = gear)) +
  geom_point(size = 3) +
  labs(
    title = "Fuel economy declines as weight increases",
    subtitle = "1973–74 Motor Trend US automobiles",
    caption = "Data: mtcars",
    x = "Weight (1000 lbs)",
    y = "Fuel economy (mpg)",
    color = "Gear count"
  )

p
查看图片ggplot2 默认主题示例
ggplot2 默认主题示例

先保留一个不依赖扩展主题的基础图,便于比较主题究竟改变了什么,也方便在扩展包不可用时回退。

使用 ggthemes 的局部主题

ggthemes 提供多种模仿报刊、软件界面和经典设计风格的主题与标度:

library(ggthemes)

p + theme_economist()
p + theme_wsj()
p + theme_tufte()
p + theme_fivethirtyeight()
p + theme_solarized()
p + theme_solarized(light = FALSE)
p + theme_excel()
p + theme_calc()
p + theme_igray()

这些函数像普通 ggplot2 主题一样加到单张图上,不会改变之后新建图形的默认状态。

常见选择包括:

函数 风格侧重
theme_economist() 报刊式背景与网格
theme_wsj() 商业报表风格
theme_tufte() 减少非必要装饰
theme_fivethirtyeight() 数据新闻风格
theme_solarized() Solarized 明暗主题
theme_excel() 电子表格风格
theme_igray() 简洁灰度外观

扩展主题只是起点,仍然可以继续使用 theme() 修改局部元素:

p +
  theme_tufte() +
  theme(
    legend.position = "bottom",
    plot.title = element_text(face = "bold")
  )

主题与颜色标度分开叠加

ggthemes 也提供颜色标度,例如:

p + scale_color_tableau()
p + scale_color_colorblind()

标度可以与主题组合:

p +
  theme_igray() +
  scale_color_colorblind()

主题不会自动保证数据颜色适合变量类型。连续变量、无序类别和有序类别需要不同的颜色逻辑;不能仅因为某套主题好看,就忽略色标是否表达了正确关系。

使用 ggthemr 设置全局风格

ggthemr 提供预设主题和调色板:

# remotes::install_github("Mikata-Project/ggthemr")
library(ggthemr)

ggthemr("dust")

设置后,新创建的 ggplot2 图会自动采用该风格:

p1 <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point(size = 3) +
  labs(title = "Dust theme")

p2 <- ggplot(mtcars, aes(wt, hp, color = factor(cyl))) +
  geom_point(size = 3) +
  labs(title = "Dust palette")

可以切换其他预设:

ggthemr("fresh")
ggthemr("pale")
ggthemr("flat")

p + theme_*() 不同,ggthemr() 会改变会话中的全局绘图状态。完成后应恢复默认,避免后续图形在没有显式代码的情况下继承旧风格:

ggthemr_reset()

自定义 ggthemr 调色板

define_palette() 可以同时定义离散色板与连续渐变:

custom_palette <- define_palette(
  swatch = c("#4477AA", "#EE6677", "#228833", "#CCBB44"),
  gradient = c(lower = "#F7FBFF", upper = "#08306B")
)

ggthemr(custom_palette)
  • swatch 用于离散类别;
  • gradient 用于连续数值;
  • 应用结束后仍使用 ggthemr_reset() 清理全局状态。

随机生成颜色适合试验 API,却不适合作为正式调色板。正式图形应检查类别之间是否容易区分、文字与背景是否有足够对比,以及灰度或常见色觉条件下是否仍能阅读。

如何选择

  • 单张图需要明确、可追踪的外观:把 theme_*()scale_*() 直接加到图对象上;
  • 多张图需要同一套局部规则:编写自己的主题函数并显式复用;
  • 临时探索中希望整个会话快速换肤:使用 ggthemr(),结束后重置;
  • 论文或长期项目:优先保留显式主题代码,减少不可见的全局状态。

主题解决一致性,调色板解决数据编码。选择扩展包时,应关注代码是否能稳定复现设计,而不只是预设样式的名字。