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

如何在R语言lattice的xyplot子图中添加主副标题?

解决lattice xyplot子图添加主副标题的问题

我明白你想用lattice的xyplot实现每个子图显示Grp作为主标题、Sub_grp作为副标题的需求——直接修改分组公式确实达不到预期,因为lattice默认的strip只会按指定分组变量依次显示,不会自动区分主副标题。下面给你两种实用的解决方法:

方法1:创建组合标签变量(简单直接)

你的数据里每个Grp对应唯一的Sub_grp,所以我们可以先生成一个包含主副标题的组合标签,再用它作为分组变量:

# 给数据框添加带换行的组合标签
d$Group_Label <- paste0(d$Grp, "\nSub_grp: ", d$Sub_grp)

# 修改xyplot代码,使用新的分组变量
xyplot(Col1 + Col2 + Col3 ~ Var | Group_Label, 
       data=d, 
       superpose=T, 
       as.table=TRUE, 
       col=c("#cc0000","#008000", "#0073e6"), 
       lwd=1.5, 
       ylim = c(0,120), 
       ylab = list(label=expression("My Values"), fontsize=15), 
       xlab = list(label="Var",fontsize=15), 
       key=list( text = list(c("Col1", "Col2", "Col3")), 
                 lines = list( lwd=1.5, col=c("#cc0000","#008000", "#0073e6")), 
                 corner = c(1, 0), x = 0.90, y = 0.17), 
       par.settings = list(strip.background=list(col="white")), 
       scales=list(cex=1.2,x=list(relation="free")), 
       type=c("l","g"),
       # 调整两行文本的字号,让主标题更突出
       strip=strip.custom(par.strip.text=list(cex=c(1.2, 0.9))))

这个方法利用换行符\n拆分主副标题,再通过par.strip.text调整字号层级,简单易上手。

方法2:自定义strip函数(灵活可控)

如果需要更精细的样式控制(比如主标题加粗、副标题用不同颜色),可以自定义strip函数:

# 自定义strip函数,实现主副标题分层展示
custom_strip <- function(which.given, which.panel, var.name, factor.levels, ...) {
  # 获取当前面板对应的Grp
  current_grp <- factor.levels[which.panel[1]]
  # 获取对应唯一的Sub_grp
  current_subgrp <- d$Sub_grp[d$Grp == current_grp][1]
  
  # 绘制主标题(加粗、大字号)
  grid.text(current_grp, y = 0.7, gp = gpar(fontsize = 12, fontface = "bold"))
  # 绘制副标题(小字号、常规字体)
  grid.text(paste0("Sub group: ", current_subgrp), y = 0.3, gp = gpar(fontsize = 10))
}

# 调用xyplot,使用自定义strip
xyplot(Col1 + Col2 + Col3 ~ Var | Grp, 
       data=d, 
       superpose=T, 
       as.table=TRUE, 
       col=c("#cc0000","#008000", "#0073e6"), 
       lwd=1.5, 
       ylim = c(0,120), 
       ylab = list(label=expression("My Values"), fontsize=15), 
       xlab = list(label="Var",fontsize=15), 
       key=list( text = list(c("Col1", "Col2", "Col3")), 
                 lines = list( lwd=1.5, col=c("#cc0000","#008000", "#0073e6")), 
                 corner = c(1, 0), x = 0.90, y = 0.17), 
       par.settings = list(strip.background=list(col="white")), 
       scales=list(cex=1.2,x=list(relation="free")), 
       type=c("l","g"),
       # 指定自定义的strip函数
       strip=custom_strip)

这个方法可以完全控制主副标题的字体、颜色、位置,适合需要个性化展示的场景。

注意事项

你的数据中每个Grp对应唯一的Sub_grp,所以上述方法均可正常工作。如果未来数据中一个Grp对应多个Sub_grp,只需微调自定义strip函数,获取当前面板对应的Sub_grp即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:12:51