Luca
Luca

Reputation: 107

Show predefined plots in a shiny app with buttons

I am trying to make a small Shiny app with radio buttons used to select a plot (predefined in the code) and show it. This is what I have:

# The plots called "Plot1" etc. are predefined in the environment.

Interface <- {
  fluidPage(
    sidebarPanel(
      radioButtons(inputId = "Question",
                   label = "Plots",
                   choices = c("A" = "Plot1", 
                               "B" = "Plot2", 
                               "C" = "Plot3"),
                   selected = "Plot1")),
    mainPanel(uiOutput('ui_plot'))
  )
}

Server <- function(input, output){
   output$barplot <- renderPlotly({   
    if (input == "A") return(Plot1)
    else if (input == "B") return(Plot2)
    else if (input == "C") return(Plot3)  
    })
}

 shinyApp(ui = Interface, server = Server)

But this is not working. I've tried replacing return() with renderPlot() but it doesn't change anything.

I'm sorry this is probably a very silly question/mistake, but it's my first time using Shiny! Thanks everyone!

Upvotes: 0

Views: 982

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

A couple of errors in your code.

In the interface: replace uiOutput('ui_plot') with plotlyOutput("barplot").

In the server:

  • replace input with input$Questions

  • replace "A" with "Plot1", etc.

That is:

output$barplot <- renderPlotly({   
    if (input$Questions == "Plot1") return(Plot1)
    else if (input$Questions == "Plot2") return(Plot2)
    else if (input$Questions == "Plot3") return(Plot3)
})

Upvotes: 1

Related Questions