0

I would like to get the coordinates of the drawn rectangle in a separate variable, also I would like the coordinates to change if I resize the rectangle.

library(plotly)

x <- 1:50
y <- rnorm(50)

fig <- plot_ly(x = ~x, y = ~y, type = 'scatter', mode = 'lines')
fig <- config(fig,modeBarButtonsToAdd = list('drawrect'))

fig

enter image description here

There is a very similar question, but none of the solutions worked for me, those solutions must be outdated by now

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
mr.T
  • 181
  • 2
  • 13

1 Answers1

2

You have to use the plotly_relayout event in a Shiny app.

library(shiny)
library(plotly)

ui <- fluidPage(
  radioButtons("plotType", "Plot Type:", choices = c("ggplotly", "plotly")),
  plotlyOutput("plot"),
  verbatimTextOutput("relayout")
)

server <- function(input, output, session) {
  
  nms <- row.names(mtcars)
  
  output$plot <- renderPlotly({
    p <- if (identical(input$plotType, "ggplotly")) {
      ggplotly(
        ggplot(mtcars, aes(x = mpg, y = wt, customdata = nms)) + geom_point()
      )
    } else {
      plot_ly(mtcars, x = ~mpg, y = ~wt, customdata = nms)
    }
    p %>% 
      layout(dragmode = "select") %>%
      config(modeBarButtonsToAdd = list("drawrect"))
  })
  
  output$relayout <- renderPrint({
    d <- event_data("plotly_relayout")
    if (is.null(d)) "Rectangle coordinates will appear here" else d
  })
  
}

shinyApp(ui, server)

enter image description here

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225