代码之家  ›  专栏  ›  技术社区  ›  Zach

在gt中为列标签行添加边框

gt r
  •  1
  • Zach  · 技术社区  · 6 月前

    是否可以为gt表的列标签行添加边框?例如:

    # Create a simple 4x4 data frame
    data <- data.frame(
      Column_1 = c("A", "B", "C", "D"),
      Column_2 = c(1, 2, 3, 4),
      Column_3 = c(5.5, 6.5, 7.5, 8.5),
      Column_4 = c(TRUE, FALSE, TRUE, FALSE)
    )
    
    # Generate a `gt` table
    gt_table <- data %>%
      gt() %>%
      tab_header(
        title = "Simple 4x4 Table",
        subtitle = "For Testing Column Labels"
      ) %>%
      tab_style(
        style = cell_borders(sides = "bottom", weight = px(1)),
        locations = list(
          cells_column_labels(),
          cells_body(rows = 1)
        )
      )
    
    # Display the table
    gt_table
    

    包含“A”的行的底部边框会出现,但列标签(即column_1、column_2等)的底部边框不会出现。 Image of generated table

    1 回复  |  直到 6 月前
        1
  •  1
  •   lroha    6 月前

    这是由于CSS规则冲突,其中应用于顶部表体和底部列标签的默认边框样式(边框宽度为2px)优先于新的1px规则。通过将此边框的现有样式规则设置为无(或宽度设置为<=1px),可以解决此问题。

    library(gt)
    
    # Generate a `gt` table
    data %>%
      gt() %>%
      tab_header(
        title = "Simple 4x4 Table",
        subtitle = "For Testing Column Labels"
      ) %>%
      tab_style(
        style = cell_borders(sides = "bottom", weight = px(1)),
        locations = list(
          cells_column_labels(),
          cells_body(rows = 1)
        )
      ) %>%
      tab_options(column_labels.border.bottom.style = "none",
                  table_body.border.top.style = "none")  
    

    enter image description here

    有关边界冲突的更多信息,请参阅 here