3

I am trying to build a shiny app that will allow user to click in multiple places on a plot, and then click a button to add these coordinates to the plot. The catch is that I will need to pass these coordinates as a vector to an external C program, so I need to make this list (vector) available externally from within the shiny app. This is what I am unable to do.

I have included a toy example below (which renders fine) and a rather sorry attempt to create such a list. What I would like with this toy example is to produce a list of x,y coordinates and then to take the x and y coordinates from this list and add them to the vectors taken from mtcars, producing an updated plot upon clicking an "accept new values" button, for example.

Any suggestions? Thanks, Matt

library(shiny)
listo <- numeric()

ui <- basicPage(
  plotOutput("plot1", click = "plot_click"),
  verbatimTextOutput("info")
)

server <- function(input, output) {
  listo2 <-numeric() #create list
  obs <- observe({listo2 = append(listo2, input$plot_clickx)}) #adding clicks to list

    output$plot1 <- renderPlot({
    plot(mtcars$wt, mtcars$mpg)
  })

  output$info <- renderText({
    paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)
  })

  }

shinyApp(ui, server)

1 Answer 1

2

You are looking for a list, that is suited for reactive programming: So ?reactiveValuesis your friend: The following code enables you to

  • save the click points in a "reactive list"

  • plot the (not yet modified) points by click of an actionButton

The Code:

library(shiny)

ui <- basicPage(
  plotOutput("plot1", click = "plot_click"),
  verbatimTextOutput("info"),
  actionButton("updateplot", "Update Plot:")
)

server <- function(input, output) {
  val <- reactiveValues(clickx = NULL, clicky = NULL)

  observe({
      input$plot_click
      isolate({
        val$clickx = c(val$clickx, input$plot_click$x)
        val$clicky = c(val$clicky, input$plot_click$y)     
      })
  }) #adding clicks to list

  output$plot1 <- renderPlot({
    plot(mtcars$wt, mtcars$mpg)
    input$updateplot
    isolate({
      points(val$clickx, val$clicky)
    })
  })

  output$info <- renderText({
    paste0("x = ", val$clickx, ", y = ",val$clicky, "\n")
  })

}

shinyApp(ui, server)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.