Michael Davidson
Michael Davidson

Reputation: 1411

R Shiny App: Size Plot Area with Input from renderPlot expr

Is it possible to alter the height of a shiny plot area according to some object created in the renderPlot expr.

Here is a simple example that almost does what I need. This sizes the window as a function of session characteristics:

library(shiny)
runApp(list(
  ui = fluidPage(
    plotOutput("plot1", height="auto")
  ),
  server = function(input, output, session) {
    output$plot1 <- renderPlot({
      plot(cars)
    }, height = function() {
      session$clientData$output_plot1_width
    })
  }
))

However, instead of sizing the plot area as a function of the session characteristics, I would like to size it based on something I calculate within the renderPlot expression (renderPlot({})), like this:

library(shiny)
runApp(list(
  ui = fluidPage(
    plotOutput("plot1", height="auto")
  ),
  server = function(input, output, session) {
    output$plot1 <- renderPlot({
      plot(cars)
    }, height = length(unique(cars$speed)))
  }
))

In this case I am creating l within renderPlot's expression and then trying to use l to size the plot area outside of the expression.

Thanks for any leads!

Upvotes: 1

Views: 658

Answers (1)

HubertL
HubertL

Reputation: 19544

You can use renderUI/uiOutput to dynamically set the height of the plot, using reactiveValues to transfer the value from the renderPlot:

runApp(list(
  ui = fluidPage(uiOutput("ui1")),
  server = function(input, output, session) {
    my <- reactiveValues(l = 500)

    output$ui1 <- renderUI(plotOutput("plot1", height=my$l))

    output$plot1 <- renderPlot({
      my$l <- length(unique(cars$speed))*100
      plot(cars)
    })
  }
))

Upvotes: 2

Related Questions