I'm working on a shiny app which "in theory" will allow the user to interactively select the hover text of values shown in a graph made using plotly::ggplotly
. Thus far, my approach has been to pass the column names from my selectizeInput
into a aes(text = paste0(...))
to try and extract both the column's name and the observation which corresponds to the (x,y) point in the plot.
If I explicitly call the columns in aes(text = paste0(...))
, it works great. However, when I try and use the selectizeInput
, I've only successfully extracted the column name and not the corresponding observation.
In the example below, I've included what works which contains the desired output in the hover text. I've also included my best attempt at using the interactive input to replicate the desired output.
To the best of my knowledge, I think my problem is that I'm not correctly telling R to use the column name both as a string and as a column. Any help or suggestions would be greatly appreciated!
# Load Libraries ----
library(tidyverse)
library(shiny)
library(shinydashboard)
# Server ----
server <- function(input, output, session){
# Generate sample values ----
set.seed(12345)
n_points <- 26
x <- sample(1:100, n_points, TRUE)
y <- sample(1:100, n_points, TRUE)
a <- seq(1:n_points)
b <- letters[seq(1:n_points)]
df <- tibble(x, y, a, b)
# Plot_works ----
output$plot_works <- plotly::renderPlotly({
pc <- df %>% ggplot(aes(x = x, y = y)) +
geom_point(aes(text = paste0("a: ", a,"\n", "b: ", b)))
p <- plotly::ggplotly(pc, tooltip = c("x", "y", "text"))
return(p)
})
# Plot_bugged ----
output$plot_bugged <- plotly::renderPlotly({
pc <- df %>% ggplot(aes(x = x, y = y)) +
geom_point(aes(text = ifelse(is.null(input$hovertext), "",
paste0(input$hovertext,": ", !!input$hovertext, collapse = "\n"))))
p <- plotly::ggplotly(pc, tooltip = c("x", "y", "text"))
return(p)
})
}
# Body ----
body <- dashboardBody(
column(width = 6,
h3("This Works"),
plotly::plotlyOutput("plot_works")
),
column(width = 6,
h3("This does not work"),
selectizeInput("hovertext", "Select point hovertext", choices = c("a", "b"), multiple = TRUE),
plotly::plotlyOutput("plot_bugged")
)
)
# UI ----
ui <- dashboardPage(
header = dashboardHeader(disable = TRUE),
sidebar = dashboardSidebar(disable = TRUE),
body = body)
# Run App ----
shinyApp(ui = ui, server = server)