htmlwidgets / sparkline

jQuery Sparkline HTML Widget for R
Other
244 stars 40 forks source link

Additional tooltip info (like date, or values from a x axis) #14

Open diegocgaona opened 8 years ago

diegocgaona commented 8 years ago

Hi,

Could be nice to implement a feature which put some extra info in the tooltip, like a date info for time series or other info coming by another vector with the same length of the current tooltip data.

I found some discussion about it about the original sparkline jquery: https://github.com/gwatts/jquery.sparkline/issues/111 https://groups.google.com/forum/?fromgroups#!topic/jquery-sparkline/WJMFn87yWq0 https://groups.google.com/forum/#!msg/jquery-sparkline/0rtcTRAuT-A/SIF_exL0tDsJ

Thanks!

timelyportfolio commented 8 years ago

I think you are asking for some helper functions, but for now here is how you can accomplish.

# try to supplement tooltip
#  https://github.com/htmlwidgets/sparkline/issues/14

library(sparkline)

# example from documentation
#  http://omnipotent.net/jquery.sparkline/#tooltips
sparkline(
  c(1,3,5,3,8),
  type="bar", 
  tooltipFormat= '{{value:levels}} - {{value}}',
  tooltipValueLookups= htmlwidgets::JS(
"
{
  levels: $.range_map({':2': 'Low', '3:6':'Medium', '7:':'High'})
}
"
  )
)

# custom tooltipFormatter
#  silly use of as.roman
sparkline(
  c(1,3,5,3,8),
  type="bar", 
  tooltipFormatter = htmlwidgets::JS(
    sprintf(
"function(sparkline, options, field){
  debugger;
  return %s[field[0].offset];
}",
      jsonlite::toJSON(paste0(as.roman(1:5)," value"))
    )
  )
)

#  silly use of as.roman
sparkline(
  c(1,3,5,3,8),
  type="bar", 
  tooltipFormatter = htmlwidgets::JS(
    sprintf(
      "function(sparkline, options, field){
  debugger;
  return %s[field[0].offset];
}",
      jsonlite::toJSON(paste0(as.roman(1:5)," value"))
    )
  )
)

#  maybe more useful date
sparkline(
  c(1,3,5,3,8),
  type="bar", 
  tooltipFormatter = htmlwidgets::JS(
    sprintf(
      "function(sparkline, options, field){
  debugger;
  return %s[field[0].offset] + '<br/>' + field[0].value;
}",
      jsonlite::toJSON(
        format(
          seq.Date(as.Date("2015-01-01"),by="month",length.out =5)
        )
      )
    )
  )
)

#  try something with array of arrays line
library(xts)

ap <- as.xts(AirPassengers)
sparkline(
  jsonlite::toJSON(
    # get array of arrays [[date1,y1],[date2,y2],...]
    t(mapply(
      function(x,y){c(as.numeric(as.Date(x)),y)},
      index(ap),
      as.vector(ap[,1])
    ))
  ),
  type = "line",
  tooltipFormatter = htmlwidgets::JS(
"
function(sp, opts, fld){
  debugger;
  return [
    '<span style=\"font-size:20px;\">',
    (new Date(fld.x*24*60*60*1000)).toString().split(' ').slice(1,4).join(' '),
    '</span>',
    fld.y + ' miles'
  ].join('<br/>');
}
"
  ),
  width = 300,
  height = 100
)
timelyportfolio commented 8 years ago

Once/if I get some feedback, I'll try to think through how best to add helpers to R.

diegocgaona commented 8 years ago

Hi @timelyportfolio, Yes, would be good a helper! I think this could be a nice enhancement to the package (and with the addComposite() would be great).

I tested your code and worked fine, that's what I want and I think it could be helpful for others too.

One argument using a vector with the additional tooltip info (for my use, I need to put dates, but other people could want use different data) would be great, and maybe some format options too, like this from your example: '<span style=\"font-size:20px;\">',.

diegocgaona commented 8 years ago

Hi @timelyportfolio , any news about it?

Thanks!!

timelyportfolio commented 8 years ago

@diegocgaona I hope I will get a chance to revisit this soon.

iainmwallace commented 7 years ago

I posted a related question on stackoverflow, on how to modify the tool tip on a sparkline embedded in a DT in a shiny app https://stackoverflow.com/questions/45179410/add-label-to-sparkline-plot-in-datatable

Any tips greatly appreciated!

timelyportfolio commented 7 years ago

Hope this helps https://stackoverflow.com/questions/45179410/add-label-to-sparkline-plot-in-datatable/45280432#45280432.

iainmwallace commented 7 years ago

That was a great solution, really helped me understand what was going on. I particularly appreciate the helper functions.

diegocgaona commented 7 years ago

Hi @timelyportfolio , any news? I tried to adapt the example now (a little late...) to use a DF with 2 columns (date and values), but my expertise is horrible... :(

There is a way you could help me?

Many thanks!!!

timelyportfolio commented 7 years ago

I have not thought of an easy way to add helpers, but I have not spent much time. Maybe another example will help me think through this. @diegocgaona, do you have some code that you could share?

diegocgaona commented 7 years ago

Unfortunately, I hadn't any useful code... I confess I'm not a good programmer and the JS you used in your example for me is out of my league :(

I didn't understood exactly how to pass the values to the secondary tool tip.

When you wrote the first time, I didn't understood very well (but it worked) and I didn't wanted to bother you with this at the time.

But no problem, if I came with some examples or ideas I will put here.

Thanks!!

dylancis commented 6 years ago

Thanks guy he example provided does not work with type='line' instead Example with:

require(sparkline)
require(DT)
require(shiny)
require(tibble)

#### helper function for adding the tooltip
spk_tool <- function(labels) {
  htmlwidgets::JS(
    sprintf(
      "function(sparkline, options, field){
      return %s[field[0].offset];
}",
    jsonlite::toJSON(labels)
    )
    )
}

# create data
spark_data1<-tribble(
  ~id,  ~spark,
  #### use sparkline::spk_chr helper
  ####   note spk_chr build for easy usage with dplyr, summarize
  # LINE FAILED
  "a", spk_chr(1:3,type="line", tooltipFormatter=spk_tool(c("C","D","E"))),
   # BAR WORKS
  "b", spk_chr(3:1,type="bar",tooltipFormatter=spk_tool(c("C","D","E")))
)

ui <- tagList(
  fluidPage(
    DT::dataTableOutput("tbl")
  ),
  #### add dependencies for sparkline in advance
  #### since we know we are using
  htmlwidgets::getDependency("sparkline", "sparkline")
) 

server <- function(input, output) {

  output$tbl <- DT::renderDataTable({
    cb <- htmlwidgets::JS('function(){debugger;HTMLWidgets.staticRender();}')

    dt <-  DT::datatable(
      as.data.frame(spark_data1),
      rownames = FALSE,
      escape = FALSE,
      options = list(
        #### add the drawCallback to static render the sparklines
        ####   staticRender will not redraw what has already been rendered
        drawCallback =  cb
      )
    )

  })

}

shinyApp(ui = ui, server = server)
thfuchs commented 4 years ago

Simply return [field.x] instead of field[0].offset in the tooltip helper function to work with type "line"