【问题标题】:Clicking through plots in Shiny app在 Shiny 应用程序中单击地块
【发布时间】:2019-02-04 00:14:23
【问题描述】:

在我的 Shiny 应用程序中,我使用 for 循环来制作不同的绘图,并且我希望用户能够单击每个绘图。我将如何实现这一点,因为它目前只是进入最终情节?

library(shiny)

server <- function(input, output, session) {

  # data
  v <- c(9,8,7,8,9,5,6,7,4,3)
  w <- c(3,4,2,3,3,3,2,3,4,5)
  x <- c(1,3,4,6,2,4,6,8,6,3)
  y <- c(4,5,2,4,2,1,2,5,7,8)
  z <- c(5,9,8,6,4,6,8,9,6,7)
  df <- data.frame(v, w, x, y, z)

  # initial plot that will allow user to change parameters (haven't implemented yet)
  output$plot <- renderPlot(plot(df[[1]],df[[2]]))

  # wait until the button is triggered
  observeEvent(input$run, {
    for (i in 5){
      output$plot <- renderPlot(plot(df[[1]],df[[i]], main = i))
    }
    })
  }

ui <- fluidPage(
  actionButton("run", "Generate"),
  plotOutput("plot")
)

shinyApp(ui = ui, server = server)

【问题讨论】:

  • @SaurabhChauhan 嗨,如果我每次迭代生成两个图,但又希望两个图一个接一个地显示怎么办?你能发消息吗,我可以给你看完整的代码。
  • 您也可以添加其他情节。尝试在ui 中再创建一个情节。添加plotOutput("plot2") 并尝试渲染此图。如果您需要进一步的帮助,请告诉我!
  • @SaurabhChauhan 我会问第二个情节的另一个问题,因为我认为你已经很好地回答了这个问题:)

标签: r shiny


【解决方案1】:

您只需要使用将保持每次点击计数的变量:

    library(shiny)
    server <- function(input, output, session) {          
      # data
      v <- c(9,8,7,8,9,5,6,7,4,3)
      w <- c(3,4,2,3,3,3,2,3,4,5)
      x <- c(1,3,4,6,2,4,6,8,6,3)
      y <- c(4,5,2,4,2,1,2,5,7,8)
      z <- c(5,9,8,6,4,6,8,9,6,7)
      df <- data.frame(v, w, x, y, z)

      # initial plot that will allow user to change parameters (haven't implemented yet)
      output$plot <- renderPlot(plot(df[[1]],df[[2]]))        

     count<-0   # This is the counter which keeps track on button count

      observeEvent(input$run, {
        count <<- count + 1 # Increment the counter by 1 when button is click
        if(count<6){
          # Draw the plot if count is less than 6
          output$plot <- renderPlot(plot(df[[1]],df[[count]],main = count))
        }
        else{
        # Reset the counter if it is more than 5
         count <- 0
        }             
      })
    }

    ui <- fluidPage(
      actionButton("run", "Generate"),
      plotOutput("plot")
    )

    shinyApp(ui = ui, server = server)

【讨论】:

    【解决方案2】:

    你可以尝试直接使用操作按钮点击计数,即输入$运行,而不是使用for循环。以下代码将一一生成图表,直到点击计数小于或等于5,然后返回初始当点击次数超过 5 时立即绘制。您可以根据自己的意愿修改 else 语句。

    observeEvent(input$run, {
    if(input$run <= 5){
      output$plot <- renderPlot(plot(df[[1]],df[[input$run]], main = input$run))
    }else output$plot <- renderPlot(plot(df[[1]],df[[2]]))
    })
    

    希望这可能会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 2020-07-09
      • 1970-01-01
      相关资源
      最近更新 更多