如何在gt包表格的跨列标题间添加贯穿全表的粗竖线
在gt包表格中为跨列标题添加贯穿表格的粗竖线
gt包默认没有直接配置跨列标题间贯穿竖线的选项,我们可以通过tab_style()结合cell_borders(),给对应列组的边界列设置粗边框,同时覆盖表头和数据行,实现竖线贯穿整个表格的效果。
完整实现代码
library(gt) library(dplyr) gtcars %>% dplyr::select( -mfr, -trim, bdy_style, drivetrain, -drivetrain, -trsmn, -ctry_origin ) %>% dplyr::slice(1:8) %>% gt(rowname_col = "model") %>% tab_spanner( label = "performance", columns = c( hp, hp_rpm, trq, trq_rpm, mpg_c, mpg_h ) ) %>% # year列右侧添加2px竖线(覆盖表头和数据行) tab_style( style = cell_borders( side = "right", weight = px(2), color = "black" ), locations = list( cells_column_labels(columns = year), cells_body(columns = year) ) ) %>% # bdy_style列右侧添加2px竖线 tab_style( style = cell_borders( side = "right", weight = px(2), color = "black" ), locations = list( cells_column_labels(columns = bdy_style), cells_body(columns = bdy_style) ) ) %>% # performance组左侧(hp列)添加2px竖线 tab_style( style = cell_borders( side = "left", weight = px(2), color = "black" ), locations = list( cells_column_labels(columns = hp), cells_body(columns = hp) ) ) %>% # performance组右侧(mpg_h列)添加2px竖线 tab_style( style = cell_borders( side = "right", weight = px(2), color = "black" ), locations = list( cells_column_labels(columns = mpg_h), cells_body(columns = mpg_h) ) ) %>% # msrp列左侧添加2px竖线 tab_style( style = cell_borders( side = "left", weight = px(2), color = "black" ), locations = list( cells_column_labels(columns = msrp), cells_body(columns = msrp) ) )
关键说明
- 核心逻辑是给每个列组的边界列设置粗边框,同时将样式应用到
cells_column_labels()(表头)和cells_body()(数据行),确保竖线贯穿整个表格。 - 针对需求,我们分别给
year右侧、bdy_style右侧、performance组的左右两侧、msrp左侧添加了2px粗的黑色竖线,精准分隔各个跨列标题区域。
内容的提问来源于stack exchange,提问作者melmo
相关产品推荐
相关产品推荐

