Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

r - Plotting the same output in two tabPanels in shiny

I'm trying to plot the same histogram in two separate tab panels within a tabBox in shiny. I can plot the data in one of the tabs, but then when I add the code for the other it seems to break the app. Below is an example of I'm trying to do:

    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)})

  }
)

In this particular example, I could just add another line in the server like this

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

and then call plot2, but my actual app is a bit more complex than the above example, so I'd like to plot plot1 in both tabs.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you create a shiny app, you are creating a HTML site and the outputs are in div containers with ids. So what you are trying without knowing is to create two div container with the same id. This will not work. For a discussion, see here: Can multiple different HTML elements have the same ID if they're different elements?

What you can do is to wrap the server code in a lapply()function and generate two ids:

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

and then call plotOutput("plot1") and plotOutput("plot2"). There are also other possibilities to use only one output in a combination with conditionalPanels(), but i think this way should work better for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...