2

I am trying to use R sparkline with gt. My question is very similar to this one Is it possible to use sparkline with gt?, but on top of simply using sparkline with gt as in the referenced question, I am trying to use it as part of the summary row. Below is the picture of what I have achieved so far. Here are my two questions:

  • How can I remove the two grey lines that are printed as part of the sparkline chart in the summary row?
  • Is there a better way to add sparkline to the summary row of a gt table?

enter image description here

library(tidyverse)
library(sparkline)
library(gt)

# toy data
df <- tibble(
  name = rep(c("A", "B"), each = 20),
  value = runif(40, min = -10, max = 10) %>% cumsum()
) %>%
  group_by(name) %>%
  mutate(
    index = row_number()
  ) %>% ungroup()

# preparing the data for the standard sparkline
regular_sparkline_df <- df %>%
  group_by(name) %>%
  summarise(
    chart = spk_chr(
      value,
      type="line"
    )
  )

# here I try to prepare the data for the summary row by getting the whole gt table and then removing the header
summary_row_sparkline_df <- df %>%
  group_by(index) %>%
  summarise(value = sum(value)) %>% ungroup() %>%
  summarise(
    chart = spk_chr(
      value,
      type="line"
    )
  ) %>%
  gt() %>%
  fmt_markdown(columns = vars(chart)) %>%
  gt:::as.tags.gt_tbl() %>%
  htmltools::attachDependencies(htmlwidgets::getDependency("sparkline")) %>%
  as.character() %>%
  gsub('<thead.+</thead>', "", .) # removing the header of the table

# building the html and adding dependencies
p_html <- regular_sparkline_df %>%
  gt() %>%
  fmt_markdown(columns = vars(chart)) %>%
  grand_summary_rows(
    columns = "chart",
    fns = list(Total = ~as.character(summary_row_sparkline_df)),
    formatter = fmt_markdown
  ) %>%
  gt:::as.tags.gt_tbl() %>%
  htmltools::attachDependencies(htmlwidgets::getDependency("sparkline"))

# seeing the table in the RStudio
print(p_html, browse = interactive())
Jakub.Novotny
  • 2,912
  • 2
  • 6
  • 21

0 Answers0