Search code examples
rdata.tabledata-visualizationr-dygraphs

Add info to the info box of a dygraph with the relevant R package


#libraries
library(data.table)
library(dygraphs)
library(xts)

#dummy data
dates <- data.table(dates  = seq.Date(as.Date("2017-03-01"), length = 14, by = "month"),
                    satisfaction = runif(14, min = 0.1, max = 1),
                    answers = runif(14, min = 100, max = 1000),
                    )

#convert to xts
xts_dates <- xts(dates, order.by = as.POSIXct(dates$dates, format = ("%Y-%m-%d")))
dygraph(xts_dates)

I want only to plot satisfaction and add the answers data either to the info box on the top right corner or elsewhere where it's visible enter image description here


Solution

  • #libraries
    library(data.table)
    library(dygraphs)
    library(xts)
    
    #dummy data
    dates <- data.table(dates  = seq.Date(as.Date("2017-03-01"), length = 14, by = "month"),
                        satisfaction = runif(14, min = 0.1, max = 1),
                        answers = runif(14, min = 100, max = 1000)
                        )
    
    #convert to xts
    xts_dates <- xts(dates, order.by = as.POSIXct(dates$dates, format = ("%Y-%m-%d")))
    xts_dates <- xts_dates[, 2:3]
    
    #create dygraph with double axes
    dygraph(xts_dates, main = "Satisfaction") %>%
      dyAxis("y", label = "Satisfaction") %>%
      dyAxis("y2", label = "Number of answers", independentTicks = TRUE) %>%
      dySeries("answers", axis = 'y2')
    

    Basically, I added an additional axis for number of answers.enter image description here