0

I'm trying to get to x/y co-ordinates of click events on R plotly indicator plots when run in Shiny. The reason I'm doing this is because there doesn't seem to be an option for tooltips on these indicator plots, so I'd like to programmatically determine which of several indicator plots the user has clicked in my Shiny app, and generate a text explainer on the side.

I can't see anything in the documentation (here and here) that indicates how to achieve this on indicator plots (or indeed, any kind of interactivity whatsoever such as tooltips).

I've tried implementing a Javascript workaround based on this answer but with no success:

library(plotly)
library(shiny)
library(htmlwidgets)

ui <- fluidPage(
  plotlyOutput("gauge"),
  verbatimTextOutput("click")
)

server <- function(input, output, session) {
  
  js <- "
    function(el, x, inputName){
      var id = el.getAttribute('id');
      var gd = document.getElementById(id);
      var d3 = Plotly.d3;
      Plotly.plot(id).then(attach);
        function attach() {
          var xaxis = gd._fullLayout.xaxis;
          var yaxis = gd._fullLayout.yaxis;
          var l = gd._fullLayout.margin.l;
          var t = gd._fullLayout.margin.t;
          var coordinates = [null, null]
    
          gd.addEventListener('click', function(evt) {
            var coordinates = [xaxis.p2c(evt.x - l), yaxis.p2c(evt.y - t)];
            Shiny.setInputValue(inputName, coordinates);
          });
        };
  }
  "
  clickposition_history <- reactiveVal(data.frame(x = 1:10, y = 1:10))
  
  observeEvent(input$clickposition, {
    clickposition_history(rbind(clickposition_history(), input$clickposition))
  })
  
  output$gauge <- renderPlotly({
    plot_ly(
      domain = list(x = c(0, 1), y = c(0, 1)),
      value = 270,
      title = list(text = "Speed"),
      type = "indicator",
      mode = "gauge+number")  %>%
      onRender(js, data = "clickposition")
  })
  
  output$click <- renderPrint({
    input$clickposition
  })
}

shinyApp(ui, server)

Any suggestions on how to enable any kind of interactivity on plotly indicator plots would be appreciated.

Sue Doh Nimh
  • 175
  • 1
  • 7

0 Answers0