Search code examples
rshinyr-highcharter

How to send a message to highcharter in Shiny to select a point


In the relatively simple shiny application below I select a point on load. Once the user chooses a new number in the selector I'd like highcharter to select that point instead. In other words, if the user selects 1 then then it should select the 1st point.

Suggestions for how to do this?

library(shiny)
library(highcharter)

ui <- function(){
  div(
    selectInput('id', label = 'select', choices = 1:3, selected = 2),
    highchartOutput("plot")
  )
}

server <- function(session, input, output){

  
  output$plot <- renderHighchart({
    hc <- highchart() %>% 
      hc_chart(events = list(load = JS("function(){this.series[0].points[2].select()}"))) %>% 
      hc_add_series(data.frame(x = 1:3, y = 1:3), "scatter", hcaes(x, y)) %>%
      hc_plotOptions(
        allowPointSelect = TRUE
      )
    
    hc
  })
  
  observeEvent(input$id, {
    # Here I'd like to send a message to the highchart
    # to select the chosen point
  })
}


shinyApp(ui, server)

Solution

  • This can be done using hcpxy_update_point function in the development version of {highcharter} (remotes::install_github("jbkunst/highcharter")).

    Be sure to use the correct id for the chart which in this case is plot.

    More examples in https://jbkunst.shinyapps.io/02-proxy-functions/.

    library(shiny)
    library(highcharter)
    
    ui <- function(){
      div(
        selectInput('id', label = 'select', choices = 1:3, selected = 2),
        highchartOutput("plot")
      )
    }
    
    server <- function(session, input, output){
    
      output$plot <- renderHighchart({
        hc <- highchart() %>% 
          hc_chart(events = list(load = JS("function(){this.series[0].points[2].select()}"))) %>% 
          hc_add_series(
            data.frame(x = 1:3, y = 1:3),
            "scatter",
            hcaes(x, y),
            id = "someid",
            ) %>%
          hc_plotOptions(
            allowPointSelect = TRUE
          )
        
        hc
      })
      
      observeEvent(input$id, {
        
        id_0_based <- as.numeric(input$id) - 1
        
        highchartProxy("plot") %>%
          # set all points unselected `selected = FALSE`
          hcpxy_update_point(id = "someid", 0:2, selected = FALSE) %>% 
          # then set to selected the _selected_ point
          hcpxy_update_point(
            id = "someid",
            id_point = id_0_based, 
            selected = TRUE
            )
      })
    }
    
    
    shinyApp(ui, server)