RShiny为Plotly图表生成下拉菜单 - 使用子元素

时间:2018-02-15 11:14:54

标签: r shiny plotly r-plotly

尝试创建一个闪亮的应用程序,该应用程序具有下拉菜单,允许您选择作为保存到全局环境的列表的子元素的图。

图表位于列表中每个元素的第二个子元素中

e.g. list = ([[dataframe1, plot1], [dataframe2, plot2], etc])

我试图创建的应用程序由:

choices = paste0("list[[1]][[", 1:2, "]]")

ui <- shinyUI(fluidPage(selectInput("selectPlot", 
                                    "Choose desired country", 
                                     choices),
                        plotlyOutput("plot")))

server <- shinyServer(function(input,output){      
   output$plot <- renderPlotly({
     return(get(input$selectPlot))
   })
 })

shinyApp(ui,server)

但是,没有显示图表,我收到以下错误: **警告:get:object&#39; anom [[1]] [[1]]&#39;找不到*

如果我将图表单独保存到环境中,那么这种方法可行。但是,我试图通过这个已经存在的列表访问这些图表!

添加可重复的示例:

ds1 <- data.frame(sample(1:10, 10), sample(11:20, 10))
ds2 <- data.frame(sample(1:10, 10), sample(11:20, 10))

p1 = plot_ly(x = ~ds1[[1]], y = ~ds1[[2]]) %>% add_markers() 
p2 = plot_ly(x = ~ds2[[1]], y = ~ds2[[2]]) %>% add_markers() 

l = list(list(ds1, p1), list(ds2, p2))

#want to access p1 and p2 from within the list to create drop down menu graph
choices.p = paste0("l[[1]][[", 1:2, "]]")

ui <- shinyUI(fluidPage(selectInput("selectPlot", 
                               "Choose desired country", 
                               choices.p), 
                               plotlyOutput("plot")))


server <- shinyServer(function(input,output){      
output$plot <- renderPlotly({
  return(get(input$selectPlot)) 
 })
})

shinyApp(ui,server)

2 个答案:

答案 0 :(得分:0)

根据您的MWE,此代码不会将图表保存在任何位置,而是使用observeEvent根据选择进行绘图。

library(shiny)
library(plotly)



ui <-shinyUI(fluidPage(selectInput("selectPlot", "Choose desired plot", choices=paste0("p", 1:2)), plotlyOutput("plot")))

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

  observeEvent(input$selectPlot,{
    if(input$selectPlot %in% 'p1') output$plot <- renderPlotly(plot_ly(mtcars, x=~cyl, y=~gear))
    else output$plot <- renderPlotly(plot_ly(mtcars, x=~hp, y=~am))

  })


})

shinyApp(ui,server)

答案 1 :(得分:0)

这样的事情对你有用:

p1 <- plot_ly(mtcars, x=~cyl, y=~gear)
p2 <- plot_ly(iris, x=~Sepal.Width, y=~Petal.Length, color = "red")

l = list(mtcars = list(mtcars, p1), iris = list(iris, p2))
choice_data <- names(l)

ui <- shinyUI(fluidPage(selectInput("selectPlot", 
                                    "Choose desired country", 
                                    choices = choice_data), textOutput("selected_var"), uiOutput("test")))


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

  output$test <- renderUI({
    l[[input$selectPlot]][2]

  })

})

shinyApp(ui,server)