R Highcharter:通过单击突出显示/取消突出显示条形图中的条形

时间:2019-01-20 06:20:14

标签: highcharts r-highcharter

是否可以在高图表条形图中突出显示单击的条形?下面的代码捕获条形图上的click事件(代码来自answer到此问题),问题是然后使用此单击信息突出显示所单击的条形图,然后在再次单击该条形图时取消突出显示或如果单击了另一个栏。

突出显示的一种方法是使用绘图带(请参见here),但是只要用户可以清楚地看到他们的选择,我就会很灵活。

library("shiny")
library("highcharter")

ui <- shinyUI(
  fluidPage(
    column(width = 8, highchartOutput("hcontainer", height = "500px")),
    column(width = 4, textOutput("text"))
  )
)

server <- function(input, output) {      

  a <- data.frame(b = LETTERS[1:10], c = 11:20, d = 21:30, e = 31:40)

  output$hcontainer <- renderHighchart({      

    canvasClickFunction <- JS("function(event) {Shiny.onInputChange('canvasClicked', [this.name, event.point.category]);}")
    legendClickFunction <- JS("function(event) {Shiny.onInputChange('legendClicked', this.name);}")

    highchart() %>% 
      hc_xAxis(categories = a$b) %>% 
      hc_add_series(name = "c", data = a$c) %>%
      hc_add_series(name = "d", data = a$d) %>% 
      hc_add_series(name = "e", data = a$e) %>%
      hc_plotOptions(series = list(stacking = FALSE, events = list(click = canvasClickFunction, legendItemClick = legendClickFunction))) %>%
      hc_chart(type = "column")

  })      

  makeReactiveBinding("outputText")

  observeEvent(input$canvasClicked, {
    outputText <<- paste0("You clicked on series ", input$canvasClicked[1], " and the bar you clicked was from category ", input$canvasClicked[2], ".") 
  })

  observeEvent(input$legendClicked, {
    outputText <<- paste0("You clicked into the legend and selected series ", input$legendClicked, ".")
  })

  output$text <- renderText({
    outputText      
  })
}

shinyApp(ui, server) 

1 个答案:

答案 0 :(得分:1)

您正在寻找 plotOptions.column.allowPointSelect 属性: API - allowPointSelect

只需更新代码中的第25行:

hc_plotOptions(series = list(stacking = FALSE, allowPointSelect = TRUE, events = list(click = canvasClickFunction, legendItemClick = legendClickFunction))) %>%

要选择1个以上的点,请按住 ctrl 按钮。