使用 renderUI() 中的反应值更新 renderPlot()

Update renderPlot() with reactive value inside renderUI()

我有一个非常大的应用程序。为了帮助它更有效地加载,我将大量数据处理放入了 observeEvent() 函数中。我希望添加的是一个滑块输入,用于更改具有反应值的直方图上的 bin 大小。

如何在不再次点击操作按钮的情况下更新剧情?

这是一个示例应用程序:

library(shiny)
library(ggplot2)

ui <- basicPage(
  actionButton("launch", "Launch"),
  uiOutput("plotInteractive")
  )

server <- function(input, output) {
  bins <- reactive({input$binsize})
  
  observeEvent(input$launch, {
  plot <- ggplot(diamonds, aes(y = carat)) +
            geom_histogram(bins = bins())
  
  output$plotInteractive <- renderUI ({
    tagList(
      renderPlot(plot),
      sliderInput(inputId = "binsize", label = "Bin Size", min = 1, max = 40, value = 20)
      )
  }) #end UI
  }) #end observe
} #end server

shinyApp(ui, server)

不要在 observeEvent 中包含 renderPlot,因为如果这样做,代码只会在您单击 Launch 按钮时执行。

我不确定为什么 sliderInputserver 一侧,因为它看起来是静态的,但在较大的应用程序中可能有意义。

library(shiny)
library(ggplot2)

ui <- basicPage(
  actionButton("launch", "Launch"),
  plotOutput('plot'),
  uiOutput("plotInteractive")
)

server <- function(input, output) {
  bins <- reactive({input$binsize})
  
  output$plot <- renderPlot({
    req(input$launch) #Show plot only after launch is clicked
    ggplot(diamonds, aes(y = carat)) +
    geom_histogram(bins = bins())
  })
  
  observeEvent(input$launch, {
    output$plotInteractive <- renderUI ({
        sliderInput(inputId = "binsize", label = "Bin Size", 
                    min = 1, max = 40, value = 20)
    }) #end UI
  }) #end observe
} #end server

shinyApp(ui, server)

最简单的解决方案是将 renderPlot 从 renderUI 函数中移出,而不是定义 plot <- renderPlot({ggplot...})

代码如下:

library(shiny)
library(ggplot2)

ui <- basicPage(
  actionButton("launch", "Launch"),
  uiOutput("plotInteractive")
  )

server <- function(input, output, session) {
  
  observeEvent(input$launch, {
    bins <- reactive({input$binsize})
    
    plot <- renderPlot({
      ggplot(diamonds, aes(y = carat)) +
            geom_histogram(bins = bins())
    })
  
  output$plotInteractive <- renderUI ({
    tagList(
      plot,
      sliderInput(inputId = "binsize", label = "Bin Size", min = 1, max = 40, value = 20)
      )
  }) #end UI
  }) #end run
  
} #end server

shinyApp(ui, server)