0
votes

In ShinyApp, I want to plot a graph whose name has an interactive input value. So in the ui.R side, the user chooses an input value from 0, 1 or 2. And in the server.R side, I want the App to plot a graph whose name is either pl0, pl1 or pl2. That is to say, if the user chooses 0 as an input value, the App plots a graph pl0, so does the same for pl1 for input 1, and for pl2 and input 2. I am using plotly library for plotting graphs.

I have tried print(), plot(), return(), but neither of them worked. Any solution or advice would be appreciated. Thank you very much!

Here is my ui.R

library(shiny)

shinyUI(fluidPage(

  # Application title
  titlePanel("Star Cluster Simulations"),

  # Sidebar with a slider input for time
  sidebarLayout(
    sidebarPanel(
      sliderInput(inputId = "time",
                  label = "Select time to display a snapshot",
                  min = 0,
                  max = 2,
                  value = 0)
    ),

    # Show a plot of the generated distribution
    mainPanel(
      plotlyOutput("distPlot")
    )
  )
))

And here is my server.R

library(shiny)
library(plotly)

# load data
for(i in 0:2) {
  infile <- paste0("Data/c_0", i, "00.csv")
  a <- read.csv(infile)
  b <- assign(paste0("c_0", i, "00"), a)
  names(a) <- paste0("c_0", i, "00")
  pl <- plot_ly(b, x = ~x, y = ~y, z = ~z, color = ~id) %>%
    add_markers() %>%
    layout(scene = list(xaxis = list(title = 'x'),
                        yaxis = list(title = 'y'),
                        zaxis = list(title = 'z')))
  assign(paste0("pl", i), pl)
}

# shinyServer
shinyServer(function(input, output) {
  output$distPlot <- renderPlotly({

    # this doesn't work
    print(paste0("pl", input$time)) 

  })
})
1

1 Answers

0
votes

I can't test this since your question isn't reproducible (i.e. doesn't include data), but one way to switch between text values (i.e. the values returned from Shiny inputs) and R objects is by making a reactive expression that uses the switch function. You can call the reactive expression (in the case below, plot.data()) inside renderPlotly (or any other render function) to switch between datasets.

shinyServer(function(input, output) {

  plot.data <- reactive({
    switch(paste0("pl", input$time),
           "pl0" = pl0,
           "pl1" = pl1,
           "pl2" = pl2)
  })

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

})