Is it possible to use sparkline with gt?

1.1k views Asked by At

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()
2

There are 2 answers

5
Paul On BEST ANSWER

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

0
Jakub.Novotny On

Here is a solution using gtExtras. Unlike with sparkline, gtExtras charts are not interactive.

library(tidyverse)
library(gtExtras)
library(gt)

df <- tibble(
  name = rep(c("A", "B"), each = 20),
  value = runif(40, min = -10, max = 10) %>% cumsum()
)


df %>%
  group_by(name) %>%
  # for gtExtras' sparkline, a list of values needs to be provided
  summarise(chart = list(value), .groups = "drop") %>%
  gt() %>%
  gt_sparkline(chart)

enter image description here