Shiny, leaflet: Link map click event with plotly highlight feature

...
I want to be able to link my leaflet map with plotly charts such that when I click on a marker on the map, the input id corresponding to the clicked marker is highlighted on the plotly chart. So far I have already created a reactive function for the map click. The challenge is how to link it to the highlight feature in plotly chart. Below is my code snippet which filters the charts corresponding to the clicked map id:

#reactive event for map click
  map_click<-reactive({
    clk=input$maps2_marker_click
    if(!is.null(clk)){
      rev_filter<-final_data %>% filter(Kiosk_Id_number==clk$id)
      return(rev_filter)
    }
    else{
      return(final_data)
    }
  }) #end map reactive function

#percentage change compared to baseline chart
  output$stacked_plot2<-renderPlotly(
    ggplotly(
      ggplot(map_click(),aes(x=Id,y=Percentage_change_compared_to_baseline
      ))+
        geom_col(aes(fill=Water_point_type))+
        labs(
          x="Kiosk ID Number",
          y="Percentage change compared to baseline") +
        theme(
          axis.title=element_text(size=9),
          axis.text.x = element_text(angle = 90),
          panel.grid = element_blank()
        )
    ) %>%
      layout(legend = list(
        orientation = "h",x=0.1,y=-0.2
      )
      )
  ) 
  

You don't strictly need shiny to make this work -- you can use crosstalk to link leaflet and plotly elements. If you're running into specific problems, you'll have to post your code and data to get help.

There are a few examples of leaflet + plotly here:

1 Like

I have included the code of what I have been able to accomplish so far.

Thanks for sharing some code to illustrate the issue, but could you format this into a reproducible example? That is a set of code or rstudio.cloud project that folks can easily get up and running to replicate your issue? Currently, this is only part of a shiny app and doesn’t include any of the data

IF you aren't familiar with best practices for shiny reprexes, check out

This will make it easier for folks to replicate your issue and offer suggestions to solve it.