Anshuman
Anshuman

Reputation: 49

How to extract Min and Max date from Highcharter stock graph?

I want to extract the Max and Min date as selected on click of usage of the visualization on highcharter "stock" graph.

Save these dates in a variable to be accessed in another place. How can these dates be accessed ?

highchart(type = "stock") %>%
hc_add_series(df, hcaes(DateTime, Count),type = "column") %>%
hc_xAxis(type = "datetime",
dateTimeLabelFormats = list(day = '%d of %b'))

Sample Data:

DateTime            Count
  <dttm>              <int>
1 2019-01-01 00:00:00     5
2 2019-01-01 01:00:00     2
3 2019-01-01 02:00:00     1
4 2019-01-01 03:00:00     2
5 2019-01-01 04:00:00     1
6 2019-01-01 05:00:00     1

Upvotes: 0

Views: 251

Answers (1)

GyD
GyD

Reputation: 4072

Not entirely sure about what you mean by min and max, date. What do you expect to happen after clicking?

1. Event creation

Create a JavaScript click event that gets and stores value.

click_event <- JS("
  function(event) {
    // Get value of clicked column
    var clickedValue = event.point.name;

    // Store it in input$bar_clicked
    Shiny.onInputChange('bar_clicked', clickedValue);
  }
")

2. Including the event

And add the click event to your Highchart object hc_plotOptions(column = list(events = list(click = click_event))). (Based on the Highcharts API documentation)

After this you will be able to use the input$bar_clicked variable anywhere in Shiny.

Full code:

library(tibble)
library(highcharter)
library(shiny)

df <- tribble(
  ~DateTime, ~Count,
  "2019-01-01 00:00:00",     5,
  "2019-01-01 01:00:00",     2,
  "2019-01-01 02:00:00",     1,
  "2019-01-01 03:00:00",     2,
  "2019-01-01 04:00:00",     1,
  "2019-01-01 05:00:00",     1
)

click_event <- JS("
  function(event) {
    // Get value of clicked column
    var clickedValue = event.point.name;

    // Store it in input$bar_clicked
    Shiny.onInputChange('bar_clicked', clickedValue);
  }
")

ui <- fluidPage(
  highchartOutput("hc"),
  verbatimTextOutput("txt")
)

server <- function(input, output, session) {
  output$hc <- renderHighchart( {
    highchart(type = "stock") %>%
      hc_add_series(df, hcaes(DateTime, Count),type = "column") %>%
      hc_xAxis(type = "datetime",
               dateTimeLabelFormats = list(day = '%d of %b')) %>% 
      hc_plotOptions(column = list(events = list(click = click_event)))
  })

  # Print the variable
  output$txt <- renderPrint( {
    input$bar_clicked
  })
}

shinyApp(ui, server)

Output

Output

Upvotes: 2

Related Questions