r - Interactive shiny app returns wrong coordinates -


i'm trying use shiny create interactive scatter plot can click on point on graph , corresponding x , y co-ordinates. works (i.e. rstudio example) base graphics (commented out) gives different , incorrect numbers using ggplot.

library(shiny) library(ggplot2)  ui <- basicpage(   plotoutput("plot1", click = "plot_click"),   verbatimtextoutput("info") )  server <- function(input, output) {   output$plot1 <- renderplot({     # plot(mtcars$wt, mtcars$mpg)     g=ggplot(mtcars,aes(wt,mpg))+geom_point()     g    })    output$info <- rendertext({     paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)   }) }  shinyapp(ui, server) 

do need add code?

one possible hack print ggplot2 object screen print() seems return coordinates in [0,1]. if note down plotting limits before, can calculate desired values.

library(shiny) library(ggplot2)  ui <- basicpage(   plotoutput("plot1", click = "plot_click"),   verbatimtextoutput("info") )  server <- function(input, output) {   output$plot1 <- renderplot({     # plot(mtcars$wt, mtcars$mpg)     g=ggplot(mtcars,aes(wt,mpg))+geom_point()       # works version 0.8.9 on: https://stackoverflow.com/questions/7705345/how-can-i-extract-plot-axes-ranges-for-a-ggplot2-object     a=ggplot_build(g)$layout$panel_ranges[[1]]     x.range <<- a$x.range     y.range <<- a$y.range      print(g)    })    output$info <- rendertext({      paste0("x=", x.range[1]+diff(x.range)*input$plot_click$x,            "\ny=", y.range[1]+diff(y.range)*input$plot_click$y)   }) }  shinyapp(ui, server) 

this works full of things might go wrong. not sure if best way.


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -