I am building a shiny application.
I am plotting charts using ggplot.
When I mouseover the points on the graph, I want a tooltip showing one of the columns in the data frame (customizable tooltip)
Can you please suggest the best way forward.
Simple App:
# ui.R
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
h4("TEst PLot")),
mainPanel(
plotOutput("plot1")
)
)
))
# server.R
library(ggplot2)
data(mtcars)
shinyServer(
function(input, output) {
output$plot1 <- renderPlot({
p <- ggplot(data=mtcars,aes(x=mpg,y=disp,color=factor(cyl)))
p <- p + geom_point()
print(p)
})
}
)
When I mouse over the points, I want it to show mtcars$wt
Using
plotly
, you can just translate yourggplot
into an interactive version of itself. Just call the functionggplotly
on yourggplot
object:For customizations of what is shown in the tooltip, look e.g. here.
You can also use a little bit JQuery and conditional
renderUI
to show a custom tooltip near the pointer.EDITED:
After this post I searched internet to see whether it could be done more nicely and found this wonderful custom tooltip for ggplot. I believe it can hardly be done better than that.
If I understand the question correctly, this can be achieved with the recent update of the shiny package for both the ggplot2 and the base package. Using this example from Winston Chang and Joe Cheng http://shiny.rstudio.com/gallery/plot-interaction-basic.html , I was able to solve this problem. Hover is now an input argument into plotOutput() so that is added to the ui along with a verbatimTextOutput to display mtcars$wt for the point hovered over.
In the server I basically make a distance vector which calculates the distance from the mouse to any point in the plot and if this distance is less than 3 (works in this application) then it shows mtcars$wt for the closest point to your mouse. To be clear input$plot_hover returns a list of info about the location of the mouse and only the x and y elements are extracted from input$plot_hover in this example.
I hope this helps!