rformattablegt

Is it possible to use sparkline with gt?


I would like to use sparkline mini charts with gt's package table. Is it possible? I know it is possible with formattable, but I would prefer to use gt tables. Here is what I want to accomplish and how to do it with formattable.

sparkline in formattable

library(tidyverse)
library(sparkline)
library(htmlwidgets) 
library(formattable)

set.seed(27)

tibble(
  name = rep(c("A", "B"), each = 20),
  value = runif(40, min = -10, max = 10) %>% cumsum()
) %>%
  group_by(name) %>%
  summarise(
    chart = spk_chr(
      value, 
      type="line")
  ) %>%
  formattable(align=c("l")) %>% 
  as.htmlwidget() %>% 
  spk_add_deps()

Solution

  • Use fmt_markdown to treat the column as HTML.

    library(tidyverse)
    library(sparkline)
    library(gt)
    
    p <- tibble(
      name = rep(c("A", "B"), each = 20),
      value = runif(40, min = -10, max = 10) %>% cumsum()
    ) %>%
      group_by(name) %>%
      summarise(
        chart = spk_chr(
          value,
          type="line")
      ) %>%
      gt() %>%
      fmt_markdown(columns = vars(chart))
    

    Then, add the dependencies using htmltools::attachDependencies

    p_html <- gt:::as.tags.gt_tbl(p)
    
    p_html <- htmltools::attachDependencies(p_html, htmlwidgets::getDependency("sparkline"))
    
    print(p_html, browse = interactive())
    

    sparklines