Search code examples
rcaptionflextable

How to change size and font of set_caption in flextable


I am looking to be able to format my flextable caption using set_caption() from the flextable package in R. I know how to format all other parts of the table except the caption. I want the caption to be "Arial" 10p font and not italicized.

Example Data

df = structure(list(Col.A = c("x", "x", "x", "x", "x", "x", "x", "x", 
"x", "x", "x", "x", "x", "x", "x"), Col.B = c("x", "x", "x", 
"x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x"), 
    Group = c("Group1", "Group1", "Group1", "Group1", "Group1", 
    "Group2", "Group2", "Group2", "Group2", "Group2", "Group3", 
    "Group3", "Group3", "Group3", "Group3"), Variable = c("V1", 
    "V2", "V3", "V4", "V5", "V1", "V2", "V3", "V4", "V5", "V1", 
    "V2", "V3", "V4", "V5")), class = "data.frame", row.names = c(NA, 
-15L))

How to make flextable

myft <- flextable(df, cwidth = c(1,1,4,1) ) %>% bg(i = NULL, j = NULL, bg = "#333D47", part = "header") %>% 
  color(i = NULL, j = NULL, color = "white", part = "header") %>% 
  bold(i = NULL, j = NULL, bold = TRUE, part = "header") %>% 
  fontsize(i = NULL, j = NULL, size = 10) %>% theme_box() %>% set_caption(caption = paste0("Table 1"))

myft

enter image description here


Solution

  • From my understanding of the docs you could achieve your desired result by defining the caption via as_paragraph() and as_chunk() which allows to set the text properties like so:

    library(flextable)
    library(magrittr)
    
    myft <- flextable(df, cwidth = c(1, 1, 4, 1)) %>%
      bg(i = NULL, j = NULL, bg = "#333D47", part = "header") %>%
      color(i = NULL, j = NULL, color = "white", part = "header") %>%
      bold(i = NULL, j = NULL, bold = TRUE, part = "header") %>%
      fontsize(i = NULL, j = NULL, size = 10) %>%
      theme_box() %>%
      set_caption(
        caption = as_paragraph(
          as_chunk(
            "Table 1",
            props = fp_text_default(font.size = 10, font.family = "Arial")
          )
        )
      )
    
    myft
    

    enter image description here