rr-dygraphs

Add a period counter on dygraphs label


For example, on a dygraph like that:

library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)
dygraph(lungDeaths)

I would like to customize the label as follows. Instead of

Jan, 1974
Feb, 1974
etc.

I would like to see:

Jan, 1974 (1)
Feb, 1974 (2)
etc.

I don't care if the counter is concatenated on the date, I just want to see the period incremental number, as the mouse moves over the series. (Of course without displaying it as a series on the graph)


Solution

  • You can create a customised valueFormatter, and use the row argument to capture the period number. Here is an example:

    library(dygraphs)
    library(htmlwidgets)
    lungDeaths <- cbind(mdeaths, fdeaths)
    
    date_counter <- 'function(d,opts, seriesName, dygraph, row, col){
                  var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                  date = new Date(d);
                  return monthNames[date.getMonth()]+", " +date.getFullYear() + " (" + row.toString() + ")";
    }'
    
    dygraph(lungDeaths) %>%
      dyAxis("x",valueFormatter=JS(date_counter))