I would like to have sparkline charts from the gtExtras package not only for my data rows but also for the summary rows in a gt table. Is this possible?
So far i have sparklines only for the raw-data-rows but not for the (grand)-summary:
library(tidyverse)
library(gt)
library(gtExtras)
these_years <- c(1980,1990,2000)
df <- countrypops |>
dplyr::filter(country_code_2 %in% c("BE", "NL", "LU",
"DK", "SE", "NO"),
year %in% these_years) |>
dplyr::mutate(region = ifelse(country_code_2 %in% c("BE", "NL", "LU"),
"Benelux",
"Scandinavia")) |>
dplyr::select(region, country_name, year, population) |>
tidyr::pivot_wider(names_from = year, values_from = population)
df |>
mutate(trend = list(c_across(where(is.numeric))), .by = country_name) |>
gt(
rowname_col = "country_name",
groupname_col = "region"
) |>
summary_rows(
groups = everything(),
columns = num_range(prefix = "", these_years),
fns = list(
Sum = ~ sum(., na.rm = TRUE)
)
) |>
grand_summary_rows(
columns = num_range(prefix = "", these_years),
fns = list(
Grand_Sum = ~ sum(., na.rm = TRUE)
),
side = c("bottom"),
missing_text = "---"
) |>
gtExtras::gt_plt_sparkline(
column = trend,
palette = c("grey40", "grey40", "grey40", "dodgerblue1", "grey40"),
type = "points",
same_limit = FALSE
)
But i would like to have the sparklines in the summary rows as well: This is what I want
I know that it would be possible to add the lines manually by adding the (grand-)summary line before generating the trend column and adding some horizontal lines for the look:
df |>
bind_rows(df |>
pivot_longer(cols = -c(region, country_name),
names_to = "year",
values_to = "value") |>
summarise(total = sum(value), .by = c(region, year)) |>
pivot_wider(names_from = year,
values_from = total) |>
mutate(country_name = "Sum"),
df |>
pivot_longer(cols = -c(region, country_name),
names_to = "year",
values_to = "value") |>
summarise(total = sum(value), .by = c(year)) |>
pivot_wider(names_from = year,
values_from = total) |>
mutate(country_name = "Grand_Sum",
region = "")) |>
mutate(trend = list(c_across(where(is.numeric))), .by = country_name) |>
gt(
#rowname_col = "country_name",
groupname_col = "region"
) |>
tab_style(
style = cell_borders(
sides = c("top", "bottom"),
weight = px(1.5),
style = "solid"
),
locations = cells_body(rows = country_name == "Sum")
) |>
gtExtras::gt_plt_sparkline(
column = trend
)