Search code examples
rshinyplotly

how do i automatically select lasso for a plotly plot in shiny


I want to create a plotly plot in shiny that only allows lasso and rectangle select. This seems to work using plotly::config. However, the zoom is still enabled. Is there a way to select lasso by default when the plot is created, so it is not possible anymore to zoom in?

So there are two goals that I have: Preventing the user from being able to zoom in and (more importantly) preselecting lasso by default.

See the following example:

library(shiny)
library(ggplot2)
library(plotly)

ui <- fluidPage(
  plotlyOutput("po")
)

server <- function(input, output, session) {
  output$po <- renderPlotly({
    p <- ggplot(iris)+geom_point(aes(x=Sepal.Width,y=Sepal.Length,color=Species))
    p <- toWebGL(p)
    # Something like
    # Plotly.relayout(graphDiv, 'dragmode', 'lasso')
    plotly::config(p, displaylogo = FALSE, modeBarButtonsToRemove = list(
      "toImage",
      "zoom2d",
      "pan2d", 
      "zoomIn2d",
      "zoomOut2d",
      "autoScale2d",
      "resetScale2d",
      "hoverClosestCartesian",
      "hoverCompareCartesian"
    ))
  })
}

shinyApp(ui, server)

Unfortunately, I do not know how I to translate this idea, I found in here: https://community.plotly.com/t/any-way-to-choose-the-lasso-select-tool-programatically-with-api/7834

Or maybe there is even another option that is possible.


Solution

  • We can simply call layout(dragmode = "lasso") on the plotly object:

    library(shiny)
    library(ggplot2)
    library(plotly)
    
    ui <- fluidPage(
      plotlyOutput("po")
    )
    
    server <- function(input, output, session) {
      output$po <- renderPlotly({
        p <- ggplot(iris)+geom_point(aes(x=Sepal.Width,y=Sepal.Length,color=Species))
        p <- toWebGL(p)
        plotly::config(p, displaylogo = FALSE, modeBarButtonsToRemove = list(
          "toImage",
          "zoom2d",
          "pan2d", 
          "zoomIn2d",
          "zoomOut2d",
          "autoScale2d",
          "resetScale2d",
          "hoverClosestCartesian",
          "hoverCompareCartesian"
        )) |> layout(dragmode = "lasso")
      })
    }
    
    shinyApp(ui, server)
    

    Run plotly::schema() and navigate layout.layoutAttributes.dragmode.description for details.