繁体   English   中英

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

[英]Update renderPlot() with reactive value inside renderUI()

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

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

这是一个示例应用程序:

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按钮时执行。

我不确定为什么你在server端有sliderInput ,因为它看起来是 static 但也许它在更大的应用程序中有意义。

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 function 移走,而不是定义 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM