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

使用labeller后ggplot2的strip.text加粗效果失效求助

解决ggplot2分面标题使用表达式后加粗失效的问题

当使用ggplot2的facet_wrap功能并通过labeller=label_parsed解析分面标题的表达式时,theme中设置strip.text=element_text(face="bold")的加粗效果会失效。

未使用labeller时的正常加粗代码

sc <- c("Ref","DJ","DT","DTHW")
vars <- c("O2","PO4","NH4","NO3")
df1 <- data.frame(scenario=rep(sc,4),variable=rep(vars,each=4),pct=runif(16,-10,10))

ggplot(df1, aes(y= scenario, x=pct)) +
  geom_col(aes( fill = scenario), position = position_dodge()) + 
  facet_wrap(vars(variable)) +
  theme (strip.text = element_text(face = "bold"))

添加表达式后加粗失效的代码

vars2plot <- c(expression(paste("Hypol. ",O[2])),expression(paste("Epil. ",PO[4]^"3-")),
               expression(paste("Epil. ",NH[4]^"+")), expression(paste("Hypol. ",NO[3]^"-")))
names(vars2plot) <- vars
df1$variable <- factor(df1$variable, levels = vars, labels = vars2plot)

ggplot(df1, aes(y= scenario, x=pct)) +
  geom_col(aes( fill = scenario), position = position_dodge()) + 
  facet_wrap(vars(variable), labeller = labeller(variable=label_parsed)) +
  theme (strip.text = element_text(face = "bold"))

解决方案

方法一:在表达式中直接指定加粗样式

label_parsed解析的是plotmath表达式,theme的strip.text设置无法覆盖plotmath的文本样式,因此需要在定义表达式时用bold()函数包裹内容:

vars2plot <- c(expression(bold(paste("Hypol. ",O[2]))),
               expression(bold(paste("Epil. ",PO[4]^"3-"))),
               expression(bold(paste("Epil. ",NH[4]^"+"))),
               expression(bold(paste("Hypol. ",NO[3]^"-"))))
names(vars2plot) <- vars
df1$variable <- factor(df1$variable, levels = vars, labels = vars2plot)

ggplot(df1, aes(y= scenario, x=pct)) +
  geom_col(aes( fill = scenario), position = position_dodge()) + 
  facet_wrap(vars(variable), labeller = labeller(variable=label_parsed)) +
  theme(strip.text = element_text(face = "bold")) # 此设置可保留,但实际生效的是表达式中的bold()

方法二:自定义labeller函数统一添加加粗

如果不想逐个修改表达式,可以自定义labeller函数,将每个标签用bold()包裹后再解析:

ggplot(df1, aes(y= scenario, x=pct)) +
  geom_col(aes( fill = scenario), position = position_dodge()) + 
  facet_wrap(vars(variable), 
             labeller = labeller(variable = function(x) {
               parse(text = paste0("bold(", as.character(x), ")"))
             })) +
  theme(strip.text = element_text(face = "bold"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:45:37