Is it possible to use sparkline with gt?
Asked Answered
O

2

5

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()
Oquinn answered 22/10, 2020 at 9:29 Comment(0)
D
9

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

Datura answered 26/10, 2020 at 6:24 Comment(5)
Is it possible to save this as a self-contained html?Oquinn
@Oquinn htmltools::save_html(p_html, "charts.html")Datura
I went with that, but it saved the js code in separate folders. If I move the html file, it will not work anymore.Oquinn
cat(repr::repr_html(p_html), file = "charts.html") should work. Also in the RStudio Viewer, Export -> Save as Web Page...Datura
Works like a charm. Thanks a lot. You are a lifesaver, Paul.Oquinn
O
2

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

Oquinn answered 29/3, 2022 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.