'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.
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 1:[1]
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())
Solution 2:[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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paul |
| Solution 2 | Jakub.Novotny |



