如何在 Shiny 中向 highcharter 发送消息到 select 点

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

在下面这个相对简单的 shiny 应用程序中,我 select 加载了一点。一旦用户在 select 中选择了一个新号码,或者我想将 highcharter 改为 select 那个点。换句话说,如果用户 selects 1 那么它应该 select 第一个点。

关于如何做到这一点的建议?

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)

这可以使用开发版 {highcharter} (remotes::install_github("jbkunst/highcharter")) 中的 hcpxy_update_point 函数来完成。

请务必为图表使用正确的 id,在本例中为 plot

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)