Search code examples
kableextra

kableExtra can't figure out how to add spec_plot


I'm trying to add a spec_plot to my kable. My data looks something like this.

present_table = data.frame(country = c("Austria", "Belgium", "Bulgaria", "Cyprus"),
                          "2010" = c(140,136,128,76),
                          "2016" = c(118,125,156,54),
                          "2017" = c(101,145,105,50),
                          "2018" = c(67,123,90,NA))

I would like to add a column with a line graph, which shows the evolution from 2010 until 2018. I've tried everything I could fine online, but I can't figure it out ...

Kable

knitr::kable(present_table, "latex", caption = title, booktabs = F,
             align = "ccccc") %>%
  kable_styling(position = "left",
                full_width = F, 
                font_size = 8) %>%
  column_spec(1:1, bold = T) %>%
  column_spec(1:2, border_left = F, border_right = F) %>%
  row_spec(0:0, bold = T, color = "white", background = ms_table_header) %>%
  row_spec(1, hline_after = F) %>% 
  row_spec(2, hline_after = F) 

Does anyone know how to do this?

Many thanks in advance!


Solution

  • Following https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf (page 12-13), you need to tidy your data first to create a list (check ptmelt and pt_list). I had to remove a couple of things from your code, since you did not supply it.

    You could try this .Rmd file:

    ---
    title: "spec_plot"
    output: pdf_document
    ---
      
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    ```
    
    ```{r pt, message=FALSE, warning=FALSE}
    library(kableExtra)
    library(tidyverse)
    
    present_table = data.frame(country = c("Austria", "Belgium", "Bulgaria", "Cyprus"),
                               "2010" = c(140,136,128,76),
                               "2016" = c(118,125,156,54),
                               "2017" = c(101,145,105,50),
                               "2018" = c(67,123,90,NA))
    colnames(present_table) <- c("country", "2010", "2016", "2017", "2018")
    
    library(reshape2)
    ptmelt <- melt(present_table, id.vars = "country") %>%
      arrange(country)
    
    pt_list <- split(ptmelt$value, ptmelt$country)
    
    present_table %>%
      mutate(line1 = "") %>%
      kbl("latex", caption = "title", booktabs = F,
                 align = "ccccc") %>%
      kable_styling(position = "left",
                    full_width = F, 
                    font_size = 8,
                    latex_options = c("hold_position")) %>%
      column_spec(1:1, bold = T) %>%
      column_spec(1:2, border_left = F, border_right = F) %>%
      row_spec(0:0, bold = T, color = "white") %>%
      row_spec(1, hline_after = F) %>%
      row_spec(2, hline_after = F) %>%
      column_spec(6, image = spec_plot(pt_list, same_lim = TRUE))
    ```
    

    Output:

    enter image description here