【问题标题】:Update renderPlot() with reactive value inside renderUI()使用 renderUI() 中的响应值更新 renderPlot()
【发布时间】:2021-11-29 08:57:36
【问题描述】:

我有一个非常大的应用程序。为了帮助它更有效地加载,我将大量数据处理放到了一个 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)

【问题讨论】:

  • 谢谢,这真的很有帮助,并引导我找到适合我的应用程序的答案。你是对的:我不得不将 renderPlot 函数从它的位置移开。问题不在于它在 observeEvent 中,而是嵌套在 renderUI 中。

标签: r shiny shinyapps shiny-reactivity


【解决方案1】:

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

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

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)

【讨论】:

    【解决方案2】:

    最简单的解决方案是从 renderUI 函数中移动 renderPlot 并改为定义 plot

    代码如下:

    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)
    

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 2016-01-28
      • 2021-03-21
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-19
      相关资源
      最近更新 更多