user3012926
user3012926

Reputation: 127

Return dataframe of click coordinates

I want to simply click on my plot, and have it return a data.frame to R listing the coordinates clicked. I've tried this:

library(shiny)
ui <- basicPage(
  plotOutput("plot1", click = "plot_click"),
  verbatimTextOutput("info")
)
server <- function(input, output) {
  output$plot1 <- renderPlot({
    plot(mtcars$wt, mtcars$mpg)
  })

  output$info <- renderText({
    paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)
  })
  output$temp <- renderTable({ 
    temp <- data.frame(input$plot_click$x,input$plot_click$y)
    return(temp)
  })
}
shinyApp(ui, server)

But 'temp' is never returned to the R environment. What am I doing wrong? How can I do this?

sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 19.10

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.8.0
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.8.0

locale:
 [1] LC_CTYPE=en_IL.UTF-8       LC_NUMERIC=C               LC_TIME=en_IL.UTF-8        LC_COLLATE=en_IL.UTF-8     LC_MONETARY=en_IL.UTF-8    LC_MESSAGES=en_IL.UTF-8   
 [7] LC_PAPER=en_IL.UTF-8       LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_IL.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] shiny_1.4.0.2

loaded via a namespace (and not attached):
 [1] compiler_3.6.1  fastmap_1.0.1   magrittr_1.5    R6_2.4.1        promises_1.1.0  later_1.0.0     htmltools_0.4.0 tools_3.6.1     Rcpp_1.0.3      jsonlite_1.6.1  digest_0.6.25  
[12] xtable_1.8-4    httpuv_1.5.2    mime_0.9        rlang_0.4.5   

Upvotes: 0

Views: 57

Answers (1)

Eli Miller
Eli Miller

Reputation: 86

Give the following a try. You should be able to use the rv$df variable in replace of temp. The issue is temp is reactive to the user so it needs to be put into a reactive context.

server <- function(input, output) {

  rv <- reactiveValues(
    df = data.frame(x=NA,y=NA)
  )

  observeEvent(input$plot_click, {
    rv$df$x <- input$plot_click$x
    rv$df$y <- input$plot_click$y
  })

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

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

Upvotes: 1

Related Questions