extract and store coordinates in the dataframe using shiny

Viewed 111

I can click and extract the coordinates from the plot. Here is the link. Can someone please tell me how can I extract and store these coordinates in a tibble?

1 Answers

A way to do it could be like this:

  1. Create a reactiveVal to store the tibble.
  2. Update the data every time a new point is selected.
library(shiny)
library(tidyverse)

ui <- basicPage(
  plotOutput("plot1", click = "plot_click",width = '1000px', height = "1000px"),
  verbatimTextOutput("info"),
  tableOutput("tibbl"),
  actionButton('save_to_global', "Save Table")
)

server <- function(input, output) {
  df <- reactiveVal(NULL)
  
  output$plot1 <- renderPlot({
    plot(mtcars$wt, mtcars$mpg)
  })
  
  output$info <- renderText({
    paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)
  })
  
  #create the table or update the values.
  observeEvent(c(input$plot_click$x, input$plot_click$y), {
    if (is.null(df())) {
      df(tibble(x = input$plot_click$x, y = input$plot_click$y))
    } else {
      df(df() %>%
           add_row(x = input$plot_click$x, y = input$plot_click$y))
    }
  })
  
  output$tibbl <- renderTable({
    df()
  })
  
  
  observeEvent(input$save_to_global, {
    assign('df_coordinates', df(), envir = .GlobalEnv)
  })
}


shinyApp(ui, server)

enter image description here

Related