5

I am using the answer in the question "ToolTip when you mouseover a ggplot on shiny" to add a mouseover functionality to a ggplot object in my shiny application. In contrast to this, I need to set coord_fixed in ggplot for my application. Here is a minimal working example:

library(shiny)
library(ggplot2)

ui <- fluidPage(
  plotOutput("plot1", height = "300px", width = "100%",
             hover = hoverOpts(id = "plot_hover")),
  verbatimTextOutput("hover_info")
)

server <- function(input, output) {

  output$plot1 <- renderPlot({
    ggplot(mtcars, aes(x=mpg,y=qsec)) + geom_point() + 
      coord_fixed(xlim=c(0,30),ylim=c(0,30))

  })

  output$hover_info <- renderPrint({
    if(!is.null(input$plot_hover))
      paste0(input$plot_hover$x, " ", input$plot_hover$y)
    })
}

shinyApp(ui, server)

Now my problem is that I do not get the correct x-coordinate. In the following screenshot the mouse pointer is near to the origin, but the returned x-value is around 9:

Mouse pointer is near to the origin, but x-coordinate is around 9

If I resize the browser window such that there is no space between the plot and the window border, the coordinates are correct. It seems to me that hoverOpts simply ignores the coord_fixed layout of ggplot.

Setting width = "300px" instead of width = "100%" could be a workaround. But this is not a real option for me, as I need in general a legend of variable width right to the plot, within the plot area.

How can I get the correct x-value?

Community
  • 1
  • 1
Patrick Roocks
  • 3,129
  • 3
  • 14
  • 28
  • I would say it is a bug. You might want to file it here: https://github.com/rstudio/shiny/issues – Mike Wise Feb 26 '16 at 23:09
  • I don't see why your workaround won't work with legends within the plot area. I tried it out, seems to work fine. – Mike Wise Feb 26 '16 at 23:12
  • If the plot area is quadratic and a legend is added to the right, then I get a white space at the top and the bottom (because of `coord_fixed`). And this causes a wrong y-coordinate. – Patrick Roocks Feb 27 '16 at 07:37
  • 1
    I opened a issue for the problem: https://github.com/rstudio/shiny/issues/1121 – Patrick Roocks Feb 27 '16 at 07:48
  • This bug has been fixed as of Jan 2017. The above code works as intended now. Should this question be closed? – divibisan Feb 14 '18 at 21:40

0 Answers0