在两个tabPanel中以闪亮的方式绘制相同的输出

时间:2017-05-26 15:24:20

标签: r shiny shinydashboard

我正在尝试在明亮的tabBox中的两个单独的选项卡面板中绘制相同的直方图。我可以在其中一个选项卡中绘制数据,但是当我为另一个选项卡添加代码时,它似乎打破了应用程序。以下是我正在尝试做的一个例子:

    library(shiny)
     library(dplyr)

data(mtcars)

body <- dashboardBody(
  fluidRow(
    tabBox(
      title = "miles per gallon",

      id = "tabset1", height = "250px",
      tabPanel("Tab1", plotOutput("plot1")),
      tabPanel("Tab2", plotOutput("plot1"), "test") # the app 'breaks' when I add in the **plotOutput("plot1")** here... however it works when I remove it
    )
    )
  )

shinyApp(
  ui = dashboardPage(
    dashboardHeader(title = "Test"),
    dashboardSidebar(),
    body
  ),
  server = function(input, output) {


      output$plot1 <- renderPlot({hist(mtcars$mpg)})

  }
)

在这个特定的例子中,我可以像这样在服务器中添加另一行

 output$plot2 <- renderPlot({hist(mtcars$mpg)})

然后调用plot2,但我的实际app比上面的例子复杂一点,所以我想在两个标签中绘制plot1。

2 个答案:

答案 0 :(得分:2)

创建闪亮的应用时,您正在创建一个HTML网站,输出位于带有ID的div容器中。所以你在不知道的情况下尝试创建两个具有相同id的div容器。这不行。有关讨论,请参阅此处:Can multiple different HTML elements have the same ID if they're different elements?

您可以做的是将服务器代码包装在lapply()函数中并生成两个ID:

lapply(1:2, function(nr){
  output[[paste0("plot", nr)]] <- renderPlot({hist(mtcars$mpg)})      
})

然后致电plotOutput("plot1")plotOutput("plot2")。还有其他可能只使用一个输出与conditionalPanels()组合,但我认为这种方式应该更适合你。

答案 1 :(得分:1)

BigDataScientist的答案很棒且可扩展性很强。

但是对于您只想重复一个或两个输出的情况,我认为最简单,最易读的解决方案是将它们全部分配给相同的渲染函数。例如,这将是:

output$plot1 <- output$plot2 <- renderPlot({ hist(mtcars$mpg) })

这是使用此解决方案的完整工作应用程序:

library(shiny)

body <- dashboardBody(
  fluidRow(
    tabBox(title = "miles per gallon", id = "tabset1", height = "250px",
      tabPanel("Tab1", plotOutput("plot1")),
      tabPanel("Tab2", plotOutput("plot2"), "test")
    )
  )
)

shinyApp(
  ui = dashboardPage(
    dashboardHeader(title = "Test"),
    dashboardSidebar(),
    body
  ),
  server = function(input, output) {
    output$plot1 <- output$plot2 <- renderPlot({ hist(mtcars$mpg) })
  }
)