SiH
SiH

Reputation: 1546

extract and store coordinates in the dataframe using shiny

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?

Upvotes: 1

Views: 429

Answers (2)

Vladimir Vinarsky
Vladimir Vinarsky

Reputation: 48

I reworked the accepted answer a little bit to remove the if-else block as I find it easier to read.

Original code:

# 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))
  }
})

Replacement:

# Create empty tibble    
df<-reactiveVal(tibble(x=numeric(),y=numeric()))
# Now add new row after each click
observeEvent(input$plot_click, {
  df(df() %>% add_row(x = input$plot_click$x, y = input$plot_click$y))
})

Upvotes: 1

jpdugo17
jpdugo17

Reputation: 7106

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

Upvotes: 1

Related Questions