Christos
Christos

Reputation: 805

R Shiny: How to assign the same plot to two different plotOutput

This post [1]: Shiny's tabsetPanel not displaying plots in multiple tabs contains a perfect example of what I want to achieve. As I don't want to create the same plot too many times but just once the solution proposed does not work for me.

The user who answered the below question mentions that it is possible to assign the same plot to two different plotOutputs which is exactly what I want to do do.

Could someone please help me figure this out?

Upvotes: 1

Views: 1899

Answers (1)

jdharrison
jdharrison

Reputation: 30425

Each plot needs a unique id so you will need multiple calls to a render type function to assign that id. If the rendering of the graph is a bottleneck you could render it once to png for example and display the graphic.

library(shiny)
runApp(list(
  ui = bootstrapPage(
    numericInput('n', 'Number of obs', 100),
    plotOutput('plot1'),
    plotOutput('plot2')
  ),
  server = function(input, output) {
    myPlot <- reactive({function(){hist(runif(input$n))}})
    output$plot1 <- renderPlot({myPlot()()})
    output$plot2 <- renderPlot({myPlot()()})
  }
))

alternatively you can define the server function as:

  server = function(input, output) {
    myPlot <- reactive({hist(runif(input$n))})
    output$plot1 <- renderPlot({myPlot()})
    output$plot2 <- renderPlot({plot(myPlot())})
  }

Upvotes: 3

Related Questions