I am editing this question to make it a little bit clearer.
I am new to Shiny. I have the MWE below, adapted slightly from https://gitlab.com/-/snippets/16220 and using mtcars
data.
It works as intended to show a tooltip for each point in the scatter plot when hovering over it.
But I would like an additional feature here. I have a selectizeInput
list with all the car models (one per point in the scatter plot). I would like that the same tooltip that appears when hovering over the point, appears as well when selecting the car model from the list.
So not only have a point tooltip appear upon hovering over it, but also upon selection of the "point ID" (the car model) in the selectizeInput
list.
Please check my MWE below. The tooltip shows when hovering, but it does not show when selecting in the selectizeInput
list yet. Not sure how to pass this info. Thanks!
library(shiny)
library(ggplot2)
ui <- pageWithSidebar(
headerPanel("Tooltips in ggplot2 + shiny"),
sidebarPanel(
uiOutput(outputId = "car_models"),
width = 3
),
mainPanel(
# this is an extra div used ONLY to create positioned ancestor for tooltip
# we don't change its position
div(
style = "position:relative",
plotOutput("scatterplot",
hover = hoverOpts("plot_hover", delay = 100, delayType = "debounce")),
uiOutput("hover_info", style = "pointer-events: none")
),
width = 7
)
)
server <- function(input, output) {
output$scatterplot <- renderPlot({
ggplot(mtcars, aes(x = mpg, y = hp)) +
geom_point()
})
output$car_models <- renderUI({
selectizeInput(inputId = "car_models", label = "Car models:",
choices = rownames(mtcars),
selected = NULL,
multiple = TRUE)
})
output$hover_info <- renderUI({
hover <- input$plot_hover
hover_function(mtcars, hover)
})
}
hover_function <- function(mtcars, hover){
point <- nearPoints(mtcars, hover, threshold = 5, maxpoints = 1, addDist = TRUE)
if (nrow(point) == 0) return(NULL)
left_px <- hover$coords_css$x
top_px <- hover$coords_css$y
# create style property for tooltip
# background color is set so tooltip is a bit transparent
# z-index is set so we are sure tooltip will be on top
style <- paste0("position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); ",
"left:", left_px + 2, "px; top:", top_px + 2, "px;")
# actual tooltip created as wellPanel
wellPanel(
style = style,
p(HTML(paste0("<b> Car: </b>", rownames(point), "<br/>",
"<b> mpg: </b>", point$mpg, "<br/>",
"<b> hp: </b>", point$hp, "<br/>",
"<b> Distance from left: </b>", left_px, "<b>, from top: </b>", top_px)))
)
}
runApp(list(ui = ui, server = server))