2

Is it possible to create a button which appears only when a point/marker has been selected in a plotly plot using conditional panels? Perhaps something similar to this?:

ui <- fluidPage(
    titlePanel("Conditional panels"),
    column(2, wellPanel(
        sliderInput("n", "Number of points:",
                    min = 10, max = 200, value = 50, step = 10))),

    column(5, plotlyOutput("scatterPlot", height = 300)), 
    column(5,conditionalPanel(
                  condition="event_data('plotly_click', source='plot').length > 0", 
                  downloadButton("mod_pdf", "Download Plots as PDF"))
    )
)

server <- function(input, output) {

    output$scatterPlot <- renderPlotly({
        x <- rnorm(input$n)
        y <- rnorm(input$n)
        df <- data.frame("x"=x, "y"=y)

     p <- plot_ly(data=df, source="plot") %>%
            add_markers(data=df, x=~x, y=~y, type="scatter", mode = "markers")

     # Test the output when a point is selected
     print(event_data('plotly_click', source='plot'))

     p
    })

}

shinyApp(ui, server)
KGee
  • 771
  • 7
  • 26
  • You can wrap the condition in a `reactive` and send it to the ui via `output`. See the answer from Stéphane Laurent [here](https://stackoverflow.com/questions/21609436/r-shiny-conditionalpanel-output-value) – Gregor de Cillia Aug 20 '18 at 19:39

1 Answers1

3

You can check the condition inside a reactive and then send the result to conditionalPanel.

## context: server.R
output$condition <- reactive({
  length(event_data('plotly_click', source='plot')) > 0
})
outputOptions(output, "condition", suspendWhenHidden = FALSE)

## context: ui.R
conditionalPanel(condition = "output.condition", ...)

If you want to know, why the call to outputOptions is necessary, please see this question.

Here is a full working version of the app

library(plotly)

ui <- fluidPage(
  titlePanel("Conditional panels"),
  column(2, wellPanel(
    sliderInput("n", "Number of points:",
                min = 10, max = 200, value = 50, step = 10))),

  column(5, plotlyOutput("scatterPlot", height = 300)), 
  column(5,conditionalPanel(
    condition="output.condition", 
    downloadButton("mod_pdf", "Download Plots as PDF"))
  )
)

server <- function(input, output) {

  output$scatterPlot <- renderPlotly({
    x <- rnorm(input$n)
    y <- rnorm(input$n)
    df <- data.frame("x"=x, "y"=y)

    plot_ly(data=df, source="plot") %>%
      add_markers(data=df, x=~x, y=~y, type="scatter", mode = "markers")
  })

  output$condition <- reactive({
    length(event_data('plotly_click', source='plot')) > 0
  })
  outputOptions(output, "condition", suspendWhenHidden = FALSE)
}

shinyApp(ui, server)
Gregor de Cillia
  • 7,397
  • 1
  • 26
  • 43