Search code examples
rgtgtextras

How to manually set the color of sparkline lines and extrema in gt_plt_sparkline() of gtExtras 0.4.3


On gtExtras 0.3.8, we can set the color of sparkline lines and extrema by parameters line_color = 'grey', range_colors = c('blue', 'red') (refer to gt_sparkline())

When gtExtras is upgraded to version 0.4.3, we need to execute the following code to plot sparkline (refer to gt_plt_sparkline()):

library(gt)
library(gtExtras)
mtcars %>%
  dplyr::group_by(cyl) %>%
  # must end up with list of data for each row in the input dataframe
  dplyr::summarize(mpg_data = list(mpg), .groups = "drop") %>%
  gt() %>%
  gt_plt_sparkline(mpg_data,
                             type = "shaded",
                             # palette =c('blue', 'red'),
                             same_limit = FALSE,
                             label = TRUE)

Out:

enter image description here

Parameters of gt_plt_sparkline() include:

gt_plt_sparkline(
   gt_object,
   column,
   type = "default",
   fig_dim = c(5, 30),
   palette = c("black", "black", "purple", "green", "lightgrey"),
   same_limit = TRUE,
   label = TRUE
)

I don't see parameters like line_color and range_colors, does that mean we won't be able to manually modify the color of lines and extremes or there are other ways to doing so?


Solution

  • Have a closer look at the docs (?gt_plt_sparkline). You could set the colors via the palette argument:

    A character string indicating the colors of various components. Order matters, and palette = sparkline color, final value color, range color low, range color high, and 'type' color (eg shading or reference lines).

    Here I an example of how tho set the colors.

    library(gt)
    library(gtExtras)
    
    sparkline <- "blue"
    final_value <- "red"
    range_low <- "yellow"
    range_high <- "purple"
    type <- "lightgrey"
    
    spkl_palette <- c(sparkline, final_value, range_low, range_high, type)
    
    gt_sparkline_tab <- mtcars %>%
      dplyr::group_by(cyl) %>%
      dplyr::summarize(mpg_data = list(mpg), .groups = "drop") %>%
      gt() %>%
      gt_plt_sparkline(mpg_data, palette = spkl_palette)
    
    gt_sparkline_tab
    

    enter image description here