I am new to shiny and plotly. What I'm trying to do is to add a trace first and then I want it to be replaced by a new one every time I click on a button.
here is my minimal example:
library(shiny)
library(plotly)
ui <- fluidPage(plotlyOutput("fig1"),
numericInput("A",
label = h5("A"),
value = "",
width = "100px"),
numericInput("B",
label = h5("B"),
value = "",
width = "100px"),
actionButton("action3", label = "Add to plot"),
actionButton("action4", label = "Remove point")
)
server <- function(input, output) {
A <- 1:5
B <- c(115, 406, 1320, 179, 440)
data <- data.frame(A, B)
fig <- plot_ly(data, x = A, y = B, type = 'scatter', mode = 'markers')
output$fig1 <- renderPlotly(fig)
observeEvent(input$action3, {
vals <- reactiveValues(A = input$A, B = input$B)
plotlyProxy("fig1") %>%
plotlyProxyInvoke("addTraces",
list(x = c(vals$A,vals$A),
y = c(vals$B,vals$B),
type = "scatter",
mode = "markers"
)
)
})
observeEvent(input$action4, {
vals <- reactiveValues(A = input$A, B = input$B)
plotlyProxy("fig1") %>%
plotlyProxyInvoke("deleteTraces")
})
}
shinyApp(ui,server)
I can add a new trace easily but they all remain on the plot. My solution was to add a new button to delete the trace but it did not work. I have already read this but I couldn't make it work.