Search code examples
rshinyggvis

A question about R shiny ggvis plot tooltips and reactivity


I have an app with a global function that makes a ggvis plot. I use a global function because I recreate the plot many times with slightly different settings. I need the tooltip to respond to some user inputs, but even when reactivity forces a recalculation of the plot, the tooltip does not seem to get recalculated. Here's an example of the issue:

library(shiny)
library(ggvis)

df = mtcars
df$name = row.names(df)

make_plot <- function(data, slider){
  hover_values <- function(x) {
    gear = data$gear[data$name == x$name]
    paste("gear times slider is:", gear*slider)
    }
  data %>% 
    ggvis(~mpg, ~hp, key := ~name) %>% 
    layer_points() %>% 
    add_tooltip(hover_values, "hover")
  }

ui <- fluidPage(
  sliderInput("slider", label = "slider:", min = 1, max = 10, value = 1),
  ggvisOutput("plot")
)

server <- function(input, output, session) {
  output$plot <- eventReactive(input$slider, {
    print("remaking plot...")
    make_plot(df, input$slider)
  }) %>% bind_shiny("plot")
}

shinyApp(ui = ui, server = server)

You can see that the tooltips are calculated using the slider input, but when you run the app, the tooltips do not change when the slider is changed. Can someone explain what is wrong with my approach or what I need to do to get this working?


Solution

  • MrFlick pointed out that I needed to move where bind_shiny() is used. The corrected code for the server function is:

    server <- function(input, output, session) {
      output$plot <- eventReactive(input$slider, {
        print("remaking plot...")
        make_plot(df, input$slider) %>% 
        bind_shiny("plot")
      })
    }