You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot分面标题中拼接变量并实现换行与部分加粗

解决方案

要实现分面标题换行、上半部分加粗且字号更大的效果,你需要用plotmath的atop()函数实现换行,结合bold()和字号控制函数(如huge()/large())设置格式,同时在mutate中逐行生成符合plotmath语法的字符串,最后用label_parsed解析。

方法1:直接构造Plotmath字符串

这种方法通过sprintf和map2_chr逐行生成可解析的plotmath字符串,代码简洁直观:

library(ggplot2)
library(dplyr)
library(purrr)

mpg_df <- mpg %>%
  select(year, manufacturer, model, cty, hwy) %>%
  filter(
    (year == 1999 & manufacturer == "audi" & model == "a4 quattro") |
      (year == 2008 & manufacturer == "dodge" & model == "ram 1500 pickup 4wd")
  ) %>%
  # 逐行生成带格式的plotmath字符串
  mutate(title = map2_chr(manufacturer, model, ~ {
    sprintf(
      "atop(bold(huge('This is the manufacturer %s')), 'This is the model %s')",
      .x, .y
    )
  }))

# 绘制图形
mpg_df %>%
  ggplot(aes(x = cty, y = hwy)) +
  geom_point() +
  facet_wrap(~ title, labeller = label_parsed) +
  theme_classic()

方法2:用bquote生成表达式再转字符串

如果更习惯用bquote嵌入变量,需要结合rowwise()逐行处理,再用deparse()把表达式转成字符串:

library(ggplot2)
library(dplyr)

mpg_df <- mpg %>%
  select(year, manufacturer, model, cty, hwy) %>%
  filter(
    (year == 1999 & manufacturer == "audi" & model == "a4 quattro") |
      (year == 2008 & manufacturer == "dodge" & model == "ram 1500 pickup 4wd")
  ) %>%
  rowwise() %>%
  mutate(title = deparse(bquote(
    atop(bold(huge("This is the manufacturer " * .(manufacturer))),
         "This is the model " * .(model))
  ))) %>%
  ungroup()

# 绘制图形
mpg_df %>%
  ggplot(aes(x = cty, y = hwy)) +
  geom_point() +
  facet_wrap(~ title, labeller = label_parsed) +
  theme_classic()

关键说明

  • 之前用\n换行无效:plotmath不识别文本换行符,必须用atop()实现上下分行。
  • 字号控制:plotmath提供huge()/large()/small()等函数调整字号,按需替换即可。
  • 变量嵌入:无论是sprintf还是bquote,核心是把动态变量正确嵌入到plotmath语法中,确保label_parsed能解析。

内容的提问来源于stack exchange,提问作者AndrewGB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:24:57