Search code examples
rshinyclickr-dygraphs

clicking on a point in dygraph in Shiny and printing out its corresponding date in POSIXct


I would like to click on a point in dygraph and get its corresponding date in "%Y-%m-%d %H:%M:%S" format. Here I've reproduced my problem:

library(dygraphs)
library(tidyverse)
library(data.table)
library(shiny)


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

set.seed(24)

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


ui <- fluidPage(
  fluidRow(
    column(width = 12,
           dygraphOutput("dygraph")
    )
  ),
  fluidRow(
    verbatimTextOutput("click")
  )
)

server <- function(input, output){
  
  output$dygraph <- renderDygraph({
    dygraph(df) 
  })
  
  output$click <- renderPrint({
    input$dygraph_click$x
  })
}

shinyApp(ui = ui, server = server)

Here is how the output looks like:

enter image description here

My problem is that it doesn't give me the right format. I tried to use the format function, but it did not work. I used the following line inside my renderprint:

format(as.POSIXct(input$dygraph_click$x), "%Y-%m-%d %H:%M:%S")

And here is the output:

enter image description here

It does not show the hour:minute:second properly.

Does anyone know how I can print out the POSIXct format of a date upon clicking on its corresponding point? I would appreciate any help.


Solution

  • You can use lubridate::ymd_hms to convert input$dygraph_click$x in POSIXct format and use format to display the output.

    output$click <- renderPrint({
        format(lubridate::ymd_hms(input$dygraph_click$x, tz = Sys.timezone()))
      })
    

    Complete code -

    library(dygraphs)
    library(tidyverse)
    library(data.table)
    library(shiny)
    
    dates <- seq(as.POSIXct("2021-01-01 05:00:00"), 
                 as.POSIXct("2021-01-05 05:00:00"), by = 8*3600)
    
    set.seed(24)
    
    df <- data.table(date = dates,
                     percentage = round(runif(length(dates), min = 0, max = 1), digits = 2)
    )
    
    ui <- fluidPage(
      fluidRow(
        column(width = 12,
               dygraphOutput("dygraph")
        )
      ),
      fluidRow(
        verbatimTextOutput("click")
      )
    )
    
    server <- function(input, output){
      
      output$dygraph <- renderDygraph({
        dygraph(df) 
      })
      
      output$click <- renderPrint({
        format(lubridate::ymd_hms(input$dygraph_click$x, tz = Sys.timezone()))
      })
    }
    
    shinyApp(ui = ui, server = server)
    

    enter image description here