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

如何在ggh4x双层嵌套分面图中仅添加外层分面分隔线?

解决方案

要仅在外层嵌套分面(feature的var1和var2之间)添加水平线,可以借助ggh4x的stat_panel_nested()统计函数定位外层分面的边界,具体修改如下:

library(data.table)
library(ggh4x)

DT <- data.table(feature = rep(c("var1","var2"),each=9),
                 ord = rep(c(1,2),each=9),
                 fold = c(1,2,3,5,1,2,3,4,5,1,2,3,5,1,2,3,4,5),
                 navn = c(rep("A",4),rep("B",5),rep("A",4),rep("B",5)))

ggplot(DT) + 
  geom_rect(aes(fill = navn),xmin = -Inf,xmax = Inf,
            ymin = -Inf,ymax = Inf) +
  # 添加外层分面的水平分隔线
  geom_hline(aes(yintercept = after_stat(y)),
             stat = "panel_nested",
             level = 1,  # 指定为外层分面层级
             colour = "black", size = 1, linetype = 1) +
  facet_nested(feature + fold ~ ord + navn, scales = "free",
               space = "free_y",
               nest_line = TRUE) +
  theme_minimal() +
  theme(strip.text.y.right = element_text(angle = 0),
        text = element_text(size=20),
        ggh4x.facet.nestline = element_line(linetype = 3)) +
  guides(fill=guide_legend(title=" "))

关键说明

  • stat = "panel_nested":ggh4x专为嵌套分面设计的统计函数,可识别分面的层级结构
  • level = 1:指定提取最外层分面的边界位置,这里对应feature的分组(var1和var2)
  • 可通过colour、size、linetype参数自定义分隔线的样式

该方法只会在var1和var2的所有面板之间添加一条水平线,不会对内层fold分面的布局产生影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 18:12:47