闪亮的plotOutput动态属性

4

我有一个基于用户输入的图表。 根据输入,图表的大小将不同。

我能动态控制图表的高度吗? 我知道在plotOutput()中有一个高度参数,但我找不到一种动态更改它的方法。

可重现的示例,当您选择A时,图表看起来很好,但如果选择B,则太高了-

library(shiny)
library(ggplot2)

df1 <- data.frame(x = 1:2000, y = rnorm(2000), type = rep(LETTERS[1:8], 250))
df2 <- data.frame(x = 1:100, y = rexp (100), type = rep(c('A','B'), 50))

ui <- shinyUI(fluidPage(title = '',
  fluidRow(selectInput("table",'', choices = c('A','B'))),
  fluidRow(plotOutput("my_plot", height = '1000px'))
  )
)

server <- shinyServer(function(input, output) {
  output$my_plot <- renderPlot({
    t <- if(input$table == 'A') df1
    else df2
    ggplot(t) + facet_grid(type~.) +
      geom_point(mapping = aes(x=x, y=y))
  }
  )
})
shinyApp(ui, server)

最后一件事,在实际应用中,我不是有两种不同的尺寸,而是根据输入需要改变尺寸。

1个回答

3
为了实现您需要的功能,您需要使用服务器端渲染。用户界面不知道图形具有什么内容以及如何动态调整任何内容。它只是接受服务器生成的内容并将其显示在屏幕上。
以下是一段代码(我认为是您需要的)。顺便说一句,我还将"data"部分放入自己的响应式函数中。您可以进一步修改我的代码,使像素高度成为“计算”而不是硬编码等等。
library(shiny)
library(ggplot2)

df1 <- data.frame(x = 1:2000, y = rnorm(2000), type = rep(LETTERS[1:8], 250))
df2 <- data.frame(x = 1:100, y = rexp (100), type = rep(c('A','B'), 50))

ui <- shinyUI(fluidPage(title = '',
                        fluidRow(selectInput("table",'', choices = c('A','B'))),
                        fluidRow(uiOutput('myPlotUI'))
)
)

server <- shinyServer(function(input, output) {
  myData <- reactive({
    if (input$table == 'A')
      df1
    else
      df2
  })
  myPlot <- reactive({
    output$myPlot <- renderPlot({
      ggplot(myData()) + facet_grid(type~.) +
        geom_point(mapping = aes(x=x, y=y))
    })
    if (input$table == 'A') {
      plotOutput('myPlot', height = '1000px')
    } else {
      plotOutput('myPlot', height = '250px')
    }
  })
  output$myPlotUI <- renderUI({
    myPlot()
  })
})
shinyApp(ui, server)

非常感谢!我不知道我可以在服务器上进行渲染。太完美了 :) - T.G.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接