rhoverr-dygraphs

How to change the hover information in dygraphs R?


I have been trying to plot a time series using dygraphs in R. I was trying to change the hover information which we get in top right of the plot.

The data has one column 'value', transformed from another column 'percentage'. In the hover info I want to show only date and percentage not value, which is plotted in the y2 axis.

Here I have reproduced the data and the dygraphs R code:

dates <- seq(as.POSIXct("2021-01-01 05:00:00"), as.POSIXct("2021-01-05 05:00:00"), by = 8*3600)

df <- data.frame(date = dates,
                 percentage = round(runif(
                   length(dates), min = 0, max = 1
                 ), digits = 2))

df$value <- df$percentage * 100

dygraph(df) %>%
  dyAxis(name = "y2") %>%
  dySeries("value", axis = "y2", pointSize = 0, strokeWidth = 0) %>%
  dyOptions(drawPoints = T, pointSize = 3)

Now in the hover info I do not want to show the label for value i.e. the label will have the date and the percentage only.

How can I omit this information from the hover info?


Solution

  • Currently there is no legendFormatter contained in the dygraphs package, so we may need a small workaround: The idea is to add CSS to the dygraph which makes the value parts invisible. Define

    MyDyGraph <- function(dygraph){
      
      dygraph$x$css <- '
            .dygraph-legend span:nth-child(2) {
              font-size: 0;
            }
      '
      dygraph
    }
    

    and call it within the construction:

    dygraph(df) |> 
      dyAxis(name = "y2") |> 
      dySeries("value", axis = "y2", pointSize = 0, strokeWidth = 0)  |> 
      dyOptions(drawPoints = T, pointSize = 3) |> 
      MyDyGraph()
    

    Then it will look like this without hovering:

    enter image description here

    And when hovering like this:

    enter image description here