在Shiny R中使用eventReactive绘制点时无法保留历史点的问题求助
Fixing Persistent Points in Your Shiny App
Hey there! Let's sort out why your plotted points keep resetting every time you click the Execute button. The core problem is that your current code doesn't store the history of coordinates you've entered—each click only plots the latest point instead of adding it to the existing set. Plus, the exists("input$execute") check isn't working as intended in Shiny (since input$execute starts at 0 and is always present once the app launches).
Here's the Corrected Code
library(shiny) ui <- fluidPage( actionButton(inputId="execute", label="Execute"), numericInput(inputId="numX", label="X", value=0), numericInput(inputId="numY", label="Y", value=0), plotOutput("plot") ) server <- function(input, output) { # Create a reactive value to store all historical coordinates rv <- reactiveValues(x = numeric(), y = numeric()) # Update the coordinate list whenever Execute is clicked observeEvent(input$execute, { rv$x <- c(rv$x, input$numX) rv$y <- c(rv$y, input$numY) }) # Render the plot with all stored points output$plot <- renderPlot({ # If we have points, plot them; otherwise show an empty plot if (length(rv$x) > 0) { plot(rv$x, rv$y, xlab = "X", ylab = "Y", pch = 16, col = "blue") } else { plot(0, 0, xlim = c(-10, 10), ylim = c(-10, 10), type = "n", xlab = "X", ylab = "Y") text(0, 0, "No points yet—click Execute to add!") } }) } shinyApp(ui = ui, server = server)
Key Changes Explained
reactiveValues: This is the critical piece—it lets us store mutable state (our growing list of coordinates) that persists across button clicks. Every time we add a new point, we updaterv$xandrv$yby appending the new values to the existing vectors.observeEvent: This listens for clicks on the Execute button and updates our coordinate storage. It doesn't return a value—it just modifies the reactive values when triggered.renderPlot: Now instead of plotting just the latest point, it uses all the stored coordinates inrv$xandrv$y. We also added a fallback for when there are no points yet, so the plot doesn't throw an error.
This way, each time you click Execute, the new point gets added to your existing plot instead of replacing it. 🎉
内容的提问来源于stack exchange,提问作者Jadd
相关产品推荐
相关产品推荐

