htmlrjsonsparklines

How to add tooltip labels in R Sparkline?


I have sample code to add sparklines to DT datatable which work except for customising the tooltip in sparkline (from the sparkline package).

library(sparkline) 
library(formattable) 
library(DT)
library(tidyverse)

## Create dataframe

data = data.frame(group = rep(c("A", "B"),3), yr_q = rep(c("2021 Q1", "2021 Q2", "2021 Q3"),2), count = c(1, 2, 3, 4, 5, 6))

## Add in column showing Trend for sparkline

data1 = data %>% group_by(group) %>% summarise("Trend" = spk_chr(count, x = yr_q, tooltipFormat = '{{x}}:{{y}}'))

## Create table (just illustrating issue)

data1 %>% formattable() %>% as.datatable() %>% spk_add_deps()

Here, the sparkline tooltip will show for Group A: '0:1', '1:3' and '2:5', when it should show '2021 Q1:1', '2021 Q2:3', '2021 Q3:5'.

I am hoping to preserve the categorical x variable in the tooltip.

However, it appears to convert to an index instead. I wonder it may be the use of spk_add_deps or other.

Not included, but if you do print(data1$Trend), the HTML/JSON scripts show the x labels as they should be, so I am confused as to where it falls through.


Solution

  • Following the docs one option would be to use the tooltipValueLookups option which allows to use a lookup table or range map to assign labels to the integer values which by default are used to index the x values.

    Note: From my understanding spk_chr only allows to pass a vector of y values.

    library(sparkline)
    library(formattable)
    library(dplyr, warn = FALSE)
    library(tibble)
    library(jsonlite)
    
    ## Create dataframe
    
    data <- data.frame(group = rep(c("A", "B"), 3), yr_q = rep(c("2021 Q1", "2021 Q2", "2021 Q3"), 2), count = c(1, 2, 3, 4, 5, 6))
    
    # Create lookup table
    labels <- data |>
      mutate(
        xlabel = as.integer(factor(yr_q)) - 1
      ) |> 
      distinct(xlabel, yr_q) |> 
      tibble::deframe() |> 
      as.list() |> 
      jsonlite::toJSON(auto_unbox = TRUE)
    
    
    data1 <- data %>%
      group_by(group) %>%
      summarise(
        Trend = spk_chr(
          count,
          tooltipFormat = "{{x:label}}:{{y}}",
          tooltipValueLookups = htmlwidgets::JS(
            sprintf(
              "
              {
                 label: $.range_map(%s)
              }
              ",
              labels
            )
          )
        )
      )
    
    data1 %>%
      formattable() %>%
      as.datatable() %>%
      spk_add_deps()
    

    enter image description here