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:
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?