Timothy Shen Timothy Shen - 3 months ago 33
R Question

How to use actionbutton as a trigger to conditionalPanel?

I have created a shiny code that plots graphs with action buttons.

Since I have both R plot and plotly plots, I want to plot them in the same Panel with their buttons are clicked. Here's a simple example:

UI:

library(shiny)

shinyUI(
fluidPage(

sidebarLayout(
sidebarPanel(

hr(),
actionButton("button1", label = "Button 1",
style='padding:4px; font-size:80%'),

hr(),
actionButton("button2", label = "Button 2",
style='padding:4px; font-size:80%'),

width = 2
),

mainPanel(

wellPanel(

conditionalPanel(
condition = "paneltype == 'A'",
plotOutput("plot",height = "1820px",width = "1250px")

),

conditionalPanel(
condition = "paneltype == 'B'",
plotlyOutput("plot",height = "auto")

)

)

)
)
)
)


Server:

paneltype = 'A'

shinyServer(function(input, output) {

observeEvent(input$button1, {
output$plot <- renderPlot({
plot(1:10)
},width = 1400)
paneltype <<- 'A'
})

observeEvent(input$button2, {
output$plot <- renderPlotly({
plot_ly(as.data.frame(1:10))
})
paneltype <<- 'B'
})

})

Answer

conditionalPanel works on client side(js), so its not see your variable.

Here you can do it on server side using renderUI

library(shiny)
library(plotly)

ui=shinyUI(
  fluidPage(

    sidebarLayout(
      sidebarPanel(

        hr(),
        actionButton("button1", label = "Button 1",
                     style='padding:4px; font-size:80%'),

        hr(),
        actionButton("button2", label = "Button 2",
                     style='padding:4px; font-size:80%'),

        width = 2
      ),

      mainPanel(

        wellPanel(


          uiOutput("plots")
        )

      )
    )
  )
)

server=shinyServer(function(input, output) {

  observeEvent(input$button1, {
    output$plots=renderUI({plotOutput("plot")})
    output$plot <- renderPlot({
      plot(1:10)
    },width = 1400)

  })

  observeEvent(input$button2, {
    output$plots=renderUI({plotlyOutput("plotly")})
    output$plotly <- renderPlotly({
      plot_ly(as.data.frame(1:10))
    })
  })

})

shinyApp(ui,server)