如何在gt()表格的tab_spanner分区之间增加列间距?
如何在gt表格的分区之间增加列间距
要提升gt表格的视觉清晰度,扩大Part 1与Part 2、Part 2与Part 3之间的列间距,你可以通过以下两种实用方法实现:
方法1:利用内置cell_borders添加透明边框模拟间距
通过给分区边界的列(Part1的最后一列char、Part2的最后一列time)添加右侧透明边框,来实现分区间的视觉间距。这种方法无需额外依赖,完全依托gt包自身功能:
library(gt) exibble |> gt(rowname_col = "row", groupname_col = "group") |> summary_rows( groups = "grp_a", columns = c(num, currency), fns = c("min", "max") ) |> grand_summary_rows( columns = currency, fns = total ~ sum(., na.rm = TRUE) ) |> tab_source_note(source_note = "This is a source note.") |> tab_footnote( footnote = "This is a footnote.", locations = cells_body(columns = 1, rows = 1) ) |> tab_header( title = "The title of the table", subtitle = "The table's subtitle" ) |> tab_spanner(label = md("**Part 1**"), columns = c(num, char), level = 2 )|> tab_spanner(label = md("**Part 2**"), columns = c(fctr, date, time), level = 2 )|> tab_spanner(label = md("**Part 3**"), columns = c(datetime, currency), level = 2) |> # 添加Part1与Part2之间的间距 tab_style( style = cell_borders( right = "20px solid transparent" ), locations = list( cells_body(columns = char), cells_column_labels(columns = char), cells_summary(columns = char), cells_grand_summary(columns = char) ) ) |> # 添加Part2与Part3之间的间距 tab_style( style = cell_borders( right = "20px solid transparent" ), locations = list( cells_body(columns = time), cells_column_labels(columns = time), cells_summary(columns = time), cells_grand_summary(columns = time) ) )
方法2:注入自定义CSS精准控制间距
如果需要更灵活的样式控制,可以直接给生成的HTML表格添加自定义CSS,调整目标列的右内边距:
library(gt) library(htmltools) # 生成基础gt表格 gt_table <- exibble |> gt(rowname_col = "row", groupname_col = "group") |> summary_rows( groups = "grp_a", columns = c(num, currency), fns = c("min", "max") ) |> grand_summary_rows( columns = currency, fns = total ~ sum(., na.rm = TRUE) ) |> tab_source_note(source_note = "This is a source note.") |> tab_footnote( footnote = "This is a footnote.", locations = cells_body(columns = 1, rows = 1) ) |> tab_header( title = "The title of the table", subtitle = "The table's subtitle" ) |> tab_spanner(label = md("**Part 1**"), columns = c(num, char), level = 2 )|> tab_spanner(label = md("**Part 2**"), columns = c(fctr, date, time), level = 2 )|> tab_spanner(label = md("**Part 3**"), columns = c(datetime, currency), level = 2) # 添加自定义CSS调整列间距 tagList( tags$style(HTML(" /* 针对Part1最后一列(char)设置右内边距 */ .gt_table .col_3 { padding-right: 25px !important; } /* 针对Part2最后一列(time)设置右内边距 */ .gt_table .col_6 { padding-right: 25px !important; } ")), gt_table )
说明
- 两种方法都可以通过调整
20px/25px的数值来控制间距大小; - 方法1的优势是无需额外加载包,样式会随gt表格一起导出(如保存为HTML);
- 方法2适合需要更复杂样式定制的场景,比如同时调整背景色、边框样式等。
内容的提问来源于stack exchange,提问作者always.learning
相关产品推荐
相关产品推荐

