R Shiny: plot with dynamical size

2019-02-17 09:57发布

问题:

I wanna have a plot with dynamic size and all should happen in the shinyUI.

Here is my code:

   shinyUI{
      sidebarPanel(
            sliderInput("width", "Plot Width", min = 10, max = 20, value = 15),
            sliderInput("height", "Plot Height", min = 10, max = 20, value = 15)
       )

        mainPanel(
            plotOutput("plot", width="15cm", height="15cm")
        )
    }

I set "15cm" only to see the plot.

I tried different methods to take the data from the sliderInputs and bring it to the plotOutput. I tried "input.height", "input$heigt" but nothing worked.

回答1:

You must use the inputs in the server side, for example here is one solution :

And the unit of the width and height must be a valid CSS unit, i'm not sure that "cm" is valid, use "%" or "px" (or an int, it will be coerced to a string with "px" at the end)

library(shiny)

runApp(list(
    ui = pageWithSidebar(
    headerPanel("Test"),
    sidebarPanel(
            sliderInput("width", "Plot Width (%)", min = 0, max = 100, value = 100),
            sliderInput("height", "Plot Height (px)", min = 0, max = 400, value = 400)
       ),
        mainPanel(
            uiOutput("plot.ui")
        )
    ),
    server = function(input, output, session) {

        output$plot.ui <- renderUI({
            plotOutput("plot", width = paste0(input$width, "%"), height = input$height)
        })

        output$plot <- renderPlot({
            plot(1:10)
        })
    }
))