首页 > 解决方案 > 使用 eventReactive 在闪亮的 R 上绘制点时出现问题

问题描述

这是我在这里的第一篇文章,所以我希望我能清楚地解释我的问题。我目前正在进入闪亮状态,并想从做一些基本的事情开始。我决定通过制作一个应用程序来挑战自己,该应用程序接受两个数字输入并在我按下操作栏时将它们绘制出来。问题是我想保留之前绘制的点。我无法让它工作,因为它不断重置情节。我尝试了许多不同的方法,但我真的不知道 points() 如何在闪亮上起作用。这是代码:

library(shiny)

ui <- fluidPage(
  actionButton(inputId="execute",label="Execute"),
  numericInput(inputId="numY",label="Y",value=0),
  numericInput(inputId="numX",label="X",value=0),
  plotOutput("plot")
)

server <- function(input, output) {
  
  coordx <- eventReactive(input$execute,{input$numX})
  coordy <- eventReactive(input$execute,{input$numY})
  
  if(!exists("input$execute"))
  {
    output$plot <- renderPlot({
      plot(x=coordx(),y=coordy())
    })
  }
  else
    output$plot <- renderPlot({
      points(x=coordx(),y=coordy())
    })
}

shinyApp(ui = ui, server = server)

先感谢您!

标签: rshiny

解决方案


正如评论者@Limey 和@fvall 所说,问题似乎是eventReactive()每次都会覆盖的问题。我所做的是将 x 和 y 坐标放在 a 中reactiveValues()。然后我放置了一个observeEvent()for any timeinput$execute被按下,写入 x 和 y 坐标来更新reactiveValues(). 这将保留旧值和新值。我还添加了一些内容tableOutput()来跟踪值:

library(shiny)

ui <- fluidPage(
  actionButton(inputId="execute",label="Execute"),
  numericInput(inputId="numY",label="Y",value=0),
  numericInput(inputId="numX",label="X",value=0),
  plotOutput("plot"),
  tableOutput("TABLE")
)

server <- function(input, output) {
  
  coord<-reactiveValues("x" = NULL, "y" = NULL)
  
  observeEvent(input$execute, {
    req(input$numY, input$numX)
      tempx<-c(isolate(coord$x), input$numX)
      tempy<-c(isolate(coord$y), input$numY)
      coord$x <- tempx
      coord$y <- tempy
  })
  
    output$plot <- renderPlot({
      req(input$execute)
      plot(x=isolate(coord$x),y=isolate(coord$y))
    })
    
    output$TABLE<-renderTable({
      data.frame("x" = coord$x, "y" = coord$y)
    })
}

shinyApp(ui = ui, server = server)

祝你好运!虽然我在此过程中遇到了麻烦,但我真的很喜欢自己学习 Shiny,我希望你也这样做!


推荐阅读