Xavier Prudent Xavier Prudent - 2 months ago 17
R Question

Passing arguments to renderPlot in R shiny

I want to plot with R shiny the variables contained in a data frame. I would hence have several plots, that is several renderPlot functions, but I want to create that data frame only once. I therefore look for a way to do something like

library(shiny)

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

## Creating and plotting the dataframe

## Calling renderPlot
output$plotxy <- renderPlot({
x = c(1,2,3)
y = c(4,5,6)
z = c(7,8,9)
d = data.frame( x, y, z )
plot( d$x, d$y )
})

output$plotxz <- renderPlot({
x = c(1,2,3)
y = c(4,5,6)
z = c(7,8,9)
d = data.frame( x, y, z )
plot( d$x, d$z )
})

output$plotzy <- renderPlot({
x = c(1,2,3)
y = c(4,5,6)
z = c(7,8,9)
d = data.frame( x, y, z )
plot( d$z, d$y )
})

})




ui <- shinyUI(
fluidPage(
plotOutput("plotxy"),
plotOutput("plotxz"),
plotOutput("plotzy")
)
)

shinyApp(ui = ui, server = server)


Would create the dataframe "d" as a global variable be a good idea? Any tip?

Answer

Here is an example using a reactive that would allow you to change the data in a single place. However, this is no different than loading the data.frame globally, unless/until you add responsive portions to the function that defines d() (e.g., changes due to inputs or re-reading from disk in response to a button click).

library(shiny)

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

  ## Creating the dataframe
  d <- reactive({
    data.frame(
      x = 1:3
      , y = 4:6
      , z = 7:9 
    )
  })

  ## Calling renderPlot
  output$plotxy <- renderPlot({
    plot( d()$x, d()$y )
  })

  output$plotxz <- renderPlot({
    plot( d()$x, d()$z )
  })

  output$plotzy <- renderPlot({
    plot( d()$z, d()$y )
  })

})




ui <- shinyUI(
  fluidPage(
    plotOutput("plotxy"),
    plotOutput("plotxz"),
    plotOutput("plotzy")
  )
)

shinyApp(ui = ui, server = server)
Comments