Search code examples
rshinytooltipsparklines

Is there a way to define X in sparkline lines, so that the tooltip describes both axes?


I want to add more detail to the sparkline tooltips.
How do I tell the sparkline what to use for x?
If I add any other variables to the spk_chr(c(Sepal.Length))it just appends them to y.

I want the tooltip to say "Sepal.Width: Sepal.Length" e.g. "3.3: 6.5". Currently, it is just showing position within the group.

(In my actual app I'm creating a time series so X would be a date)

library(shiny)
library(dplyr)
library(sparkline)
library(DT)

ui <- fluidPage(
    
    htmlwidgets::getDependency('sparkline'),
    dataTableOutput("table")
)


server <- function(input, output) {
    
    cb <- htmlwidgets::JS('function(){debugger;HTMLWidgets.staticRender();}')
    
    mydata <- iris %>%
        group_by(Species) %>%
        arrange(Sepal.Width) %>% 
        summarise(
            "Sepal Length" = spk_chr(
                c(Sepal.Length),
                tooltipFormat = '{{x}}: {{y}}'
            ))
    
    output$table <- renderDataTable({
        datatable(
            data = mydata,
            escape = FALSE,
            options = list(drawCallback = cb)
            )
    })
    
}

shinyApp(ui = ui, server = server)

Solution

  • I worked it out. Annoyingly simple. Add xvalues = Sepal.Width into spk_chr() This causes some issues with grouping using this example data set, but when the x values are all unique it works.

        mydata <- iris %>%
            group_by(Species) %>%
            arrange(Sepal.Width) %>% 
            summarise(
                "Sepal Length" = spk_chr(
                    c(Sepal.Length),
                    xvalues = Sepal.Width,
                    tooltipFormat = '{{x}}: {{y}}'
                ))