Shiny - actionButton:无需点击即可渲染

时间:2016-01-11 10:06:49

标签: r rendering shiny action-button

在下面的简单示例中,使用按钮刷新后,图形将呈现来自checkboxGroupInput的输入的函数。 在应用程序首次启动时,selectInput s1提供了所选复选框。

# ui.R
library(shiny)
shinyUI(fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("s1", "Select 1", 1:5)
    ),
      mainPanel(
        plotOutput("myplot"),
        uiOutput("chk.output"),
        actionButton("refresh", "Refresh")
      )
    )
  )
)
# server.R
library(shiny)
shinyServer(function(input, output, session) { 
  output$chk.output <- renderUI(checkboxGroupInput("Chk", label = "Choices", choices = list("1" = 1, "2" = 2, "3"= 3, "4"=4, "5"=5), selected = input$s1, inline = TRUE, width = "100%"))
  selectGrEv <- eventReactive(input$refresh, {input$Chk}, ignoreNULL = FALSE)
  output$myplot <- renderPlot({ 
    plot(1:5, 1:5)
    if (1 %in% selectGrEv()) {text(1,1, labels= 1, col = "red", pos = 3)}
    if (2 %in% selectGrEv()) {text(2,2, labels= 2, col = "blue", pos = 3)}
    if (3 %in% selectGrEv()) {text(3,3, labels= 3, col = "black", pos = 3)}
    if (4 %in% selectGrEv()) {text(4,4, labels= 4, col = "orange", pos = 3)}
    if (5 %in% selectGrEv()) {text(5,5, labels= 5, col = "green", pos = 1)}
  })
})

当用户更改input$s1时,checkboxGroupInput会刷新,但不会显示正常的情节。 我想通过点击“刷新”按钮或更改input$s1来刷新情节。

我尝试通过添加server.R的计数器来修改reactiveValues

# server.R
library(shiny)
shinyServer(function(input, output, session) { 
  output$chk.output <- renderUI(checkboxGroupInput("Chk", label = "Choices", choices = list("1" = 1, "2" = 2, "3"= 3, "4"=4, "5"=5), selected = input$s1, inline = TRUE, width = "100%"))

  values <- reactiveValues(cpt = 0) # Here code was added
  observeEvent(input$s1, values$cpt <- values$cpt + 1) # Here code was added

  selectGrEv <- eventReactive(input$refresh | values$cpt, {input$Chk}, ignoreNULL = FALSE) # Here code was modified
  output$myplot <- renderPlot({ 
    plot(1:5, 1:5)
    if (1 %in% selectGrEv()) {text(1,1, labels= 1, col = "red", pos = 3)}
    if (2 %in% selectGrEv()) {text(2,2, labels= 2, col = "blue", pos = 3)}
    if (3 %in% selectGrEv()) {text(3,3, labels= 3, col = "black", pos = 3)}
    if (4 %in% selectGrEv()) {text(4,4, labels= 4, col = "orange", pos = 3)}
    if (5 %in% selectGrEv()) {text(5,5, labels= 5, col = "green", pos = 1)}
  })
})

values$cpt会在input$s1更改时更改,但不会更改selectGrEv(),因此不会刷新图表。

当用户更改input$s1时,如何刷新渲染的图?

1 个答案:

答案 0 :(得分:1)

我只知道一个(可能不是好的变种)

尝试

Benchmark                          Mode  Cnt         Score         Error  Units
LogBenchmark.stringConcatenation  thrpt    5   9080147,269 ?  988134,269  ops/s
LogBenchmark.stringBuilder        thrpt    5  27136050,849 ? 2776464,863  ops/s
LogBenchmark.logback              thrpt    5   3579746,331 ?  346554,072  ops/s
LogBenchmark.log4j                thrpt    5   4992342,169 ?  335971,537  ops/s