2

I'm very new to R, so this is probably super obvious, but I'm really stuck!

I have five existing plotly charts already created. I want to be able to select them in shiny from a dropdown. I can't get the link between the existing chart names and the dropdown to work.

My latest attempt (which does not work):

ui <-shinyUI(fluidPage(selectInput("selectPlot", "Select Year:", 
choices = c("2015", "2016", "2017", "2018", "Average price across US"), 
selected = "Average price across US", plotlyOutput("plot"))))

server <- shinyServer(function(input,output){    
  output$plot <- renderPlotly({
    if(input$selectPlot == '2015') {
      p <- gg1
    }
    if(input$selectPlot == '2016') {
      p <- gg2
    }
    if(input$selectPlot == '2017') {
      p <- gg3
    }
    if(input$selectPlot == '2018') {
      p <- gg4
    }
    if(input$selectPlot == 'Average price across US') {
      p <- gg5
    }
    return(p)
  })
})

shinyApp(ui,server)

I am trying to get gg1 to show when "2015" is selected, etc.

Anavrinny
  • 23
  • 3

1 Answers1

2

Try this:

library(shiny)
library(plotly)

ui <- shinyUI(
    fluidPage(
        selectInput("selectPlot", "Select Year:", c("2015", "2016", "2017", "2018", "Average price across US"), 
                    selected = "Average price across US"),
        plotlyOutput("plot")
    )
)

server <- shinyServer(function(input,output,session){   

    data <- eventReactive(input$selectPlot,{
        switch(input$selectPlot,
               "2015" = gg1,
               "2016" = gg2,
               "2017" = gg3,
               "2018" = gg4,
               "Average price across US" = gg5)
    })

    output$plot <- renderPlotly({
        data()
    })
})

shinyApp(ui,server)
Pork Chop
  • 28,528
  • 5
  • 63
  • 77
  • Pork Chop, Could you please look at these two questions? https://stackoverflow.com/questions/61569169/plot-scatterplot-on-a-map-in-shiny https://stackoverflow.com/questions/61559805/link-selectinput-with-sliderinput-in-shiny?noredirect=1#comment108896301_61559805 –  May 03 '20 at 04:12
  • So `gg` 1 to 5 objects will go inside `renderPlotly({})`? – Ed_Gravy Oct 02 '21 at 05:14