Shiny allow users to choose which plot outputs to display

牧云@^-^@ 提交于 2021-01-28 05:29:26

问题


I have a shiny app and my server function looks like this:

shinyServer(function(input, output, session) {
 filedata <- reactive({
  infile <- input$file1
  if (is.null(infile)) {
    return(NULL)
  }
  myDF <- fread(infile$datapath)
  return(myDF)
  # Return the requested graph
graphInput <- reactive({
switch(input$graph,
       "Plot1" = plot1,
       "Plot2" = plot2)
})
 output$selected_graph <- renderPlot({ 
paste(input$graph)
  })

 output$plot1 <- renderPlot({
 #fill in code to create a plot1
})

output$plot2 <- renderPlot({
 #fill in code to create plot2
})

The UI function looks like this:

shinyUI(pageWithSidebar(
 headerPanel("CSV Viewer"),

 sidebarPanel(
  fileInput('file1', 'Choose CSV File',
          accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
  selectInput("graph", "Choose a graph to view:", 
            choices = c("Plot1", "Plot2"))
  submitButton("Update View")
),#end of sidebar panel

mainPanel(
tabsetPanel(
  tabPanel("Graph Viewer", plotOutput("selected_graph"))

)

I can't make the selected plot display on the screen. When I make a selection from the drop-down menu and click the "Update View" button the app does not display the plot. It does not display an error message. It displays nothing at all.

How can I fix this?


回答1:


As mentioned in the comments, it's difficult to ensure that any answer will work, given the incomplete example in your question. Based on the skeleton server provided, however, this pattern for selecting a graph should work:

shinyServer(function(input, output, session) {
  filedata <- reactive({
    # Haven't tested that this will read in data correctly;
    # assuming it does
    infile <- input$file1
    if (is.null(infile)) {
      return(NULL)
    }
    myDF <- fread(infile$datapath)
    return(myDF)
  })

  plot1 <- reactive({
   # this should be a complete plot image,
   # e.g. ggplot(data, aes(x=x, y=y)) + geom_line()
  })

  plot2 <- reactive({
   # this should be a complete plot image,
   # e.g. ggplot(data, aes(x=x, y=y)) + geom_line()
  })

  # Return the requested graph
  graphInput <- reactive({
   switch(input$graph,
          "Plot1" = plot1(),
          "Plot2" = plot2()
          )
  })

  output$selected_graph <- renderPlot({ 
   graphInput()
  })
}

What changed:

  • plot1 and plot2 are reactive functions (and not outputs) that can be returned from the graphInput reactive function
  • graphInput returns the value (i.e. plot) of either plot1 or plot2 into output$selected_graph


来源:https://stackoverflow.com/questions/48312392/shiny-allow-users-to-choose-which-plot-outputs-to-display

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!