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

如何在ggplot2的facet_wrap标签中仅将部分文本设为粗体

解决ggplot2分面标签部分内容加粗并兼容>符号的问题

方法一:使用ggplot2 3.3.0+的markdown标签(推荐)

从ggplot2 3.3.0版本开始,支持通过element_markdown()渲染markdown格式文本,直接用**包裹需要加粗的部分,无需转义>符号:

library(ggplot2)

# 构造示例数据,分面标签直接用markdown格式
df <- data.frame(
  x = rnorm(100),
  y = rnorm(100),
  facet = c(rep("**A** matches > 30", 50), rep("**B** matches > 60", 50))
)

# 绘图时设置strip.text为element_markdown()
ggplot(df, aes(x, y)) +
  geom_point() +
  facet_wrap(~facet) +
  theme(strip.text = element_markdown())

方法二:兼容旧版本的plotmath语法

如果你的ggplot2版本低于3.3.0,可使用plotmath表达式实现加粗,用bold()函数包裹需要加粗的字符,>符号直接写入表达式:

library(ggplot2)

df <- data.frame(
  x = rnorm(100),
  y = rnorm(100),
  # 定义原始分面标识
  facet_raw = c(rep("A", 50), rep("B", 50))
)

# 绘图时通过labeller动态生成plotmath表达式
ggplot(df, aes(x, y)) +
  geom_point() +
  facet_wrap(~facet_raw, 
             labeller = labeller(facet_raw = function(x) {
               lapply(x, function(label) {
                 if(label == "A") {
                   expression(bold(A)~matches~"> 30")
                 } else {
                   expression(bold(B)~matches~"> 60")
                 }
               })
             }))

你之前的问题根源在于:label_parsed仅识别plotmath语法,不支持HTML的<strong>标签;而使用markdown方法时,必须显式设置strip.text = element_markdown()才能解析**加粗标记。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:55:32