Reputation: 943
I'm trying to use Shiny to create an interactive scatter plot where I can click on any point on the graph and get the corresponding x and y co-ordinates. It works (i.e. is the RStudio example) for base graphics (commented out) gives different and 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 I need to add anything to my code?
Upvotes: 1
Views: 703
Reputation: 943
With many thanks for Marco's comment, this was indeed a version number issue. Updating to the most recent Shiny version resolved the problem. Now the 'correct' version works whilst my hack, as for Marco, does not. I'm now on Shiny 1.0.4 and ggplot2 2.2.0.
Upvotes: 0
Reputation: 943
One possible hack is to print the ggplot2 object to the screen with print() which then seems to return coordinates in [0,1]. If you note down the plotting limits before, you can then calculate the 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 from 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 but is obviously full of things that might go wrong. Not sure if this is the best way.
Upvotes: 1