Set {gt} table header height

Viewed 56

Is there any way to set a {gt} table header to a specific height?

I have a collection of tables, all with same width. Depending on how long is the text on the title, it breaks a line and the header height increases. It is great for a single table, but I need each table in the collection to match their heights.

At the moment, I am able to add the option heading.padding = 20, but this is added also when the line is broken. I can set it to be applied only when the title has more than n characters, but it won't work to a generic case - besides, it's not elegant. I took some shots using gt::html() but no success yet.

Here's an example:

require(dplyr)
require(gt)

iris %>% 
  select(1,2) %>% 
  gt() %>% 
  tab_header(title = "Test") %>% 
  tab_options(heading.padding = 20,
              table.width = 10)

iris %>% 
  select(1,2) %>% 
  gt() %>% 
  tab_header(title = "Testing a longer title to set the height") %>% 
  tab_options(heading.padding = 20,
              table.width = 10)

Both tables above should have the same height. Any tips to achieve that will be appreciated.

Thanks in advance!

1 Answers

EDIT:Added option 2

Try using this function that will change the heading.padding

Option 1: according to the number of characters in your title:

require(dplyr)
require(gt)

Create.table <- function(title) {
  if (nchar(title) > 22) {
    my.table <- iris %>%
      select(1, 2) %>%
      gt() %>%
      tab_header(title = title) %>%
      tab_options(heading.padding = "inherit",
                  table.width = 10)
  } else {
    my.table <- iris %>%
      select(1, 2) %>%
      gt() %>%
      tab_header(title = title) %>%
      tab_options(heading.padding = 14.46,
                  table.width = 10)
    return(my.table)
  }
}


tbl1 <- Create.table(title = "Testing a longer title to set the height")


tbl2 <- Create.table(title = "Test")

enter image description here

Option 2: Add line breaks to your title (from @Rodrigo Salvador's comment). In this case we need the package stringr to look for line breaks:

require(dplyr)
require(gt)
require(stringr)

Create.table <- function(title) {

  if (str_count(title, '<br>') > 0) { 
   my.table <- iris %>%
      select(1, 2) %>%
      slice_head() %>% 
      gt() %>%
      tab_header(title = md(title)) %>%  # markdown title
      tab_options(heading.padding = "inherit",
                  table.width = 10)
    
  } else {
 my.table <- iris %>%
      select(1, 2) %>%
      slice_head() %>% 
      gt() %>%
      tab_header(title = md(title)) %>% 
      tab_options(heading.padding = 14.46,
                  table.width = 10)
    return(my.table)
  }
}

tbl1 <- Create.table(title = "Testing a longer title <br>to set the height")

tbl2 <- Create.table(title = "Test")

tbl3 <- Create.table(title = "Loooooooooooooooooooooooooooooooooooooooooong")

enter image description here

Related