简体   繁体   中英

R shiny ggvis tooltip will not update information with new data, even though plot updates

So I have a ggvis plot within a shiny application, which is a histogram that that displays the count of observations in a bin when the user hovers over the bin. The data is randomly generated and the user can hit a button to sample a new batch of data. Everything works fine except that after a new batch of data is sampled and plotted, the tooltip still displays the counts in each bin from the original data, which of course does not match with the current data. Is there a way to fix this? Below is my minimal reproducible example.

toolTipFunc <- function(value) {
  function(y) {
    if (is.null(y)) return(NULL)
    else {
      length(value[(value >= y$xmin_) & (value < y$xmax_)])
    }
  }
}


library(shiny)
library(ggvis)

runApp(list(

ui = pageWithSidebar(
div(),
sidebarPanel(
   actionButton("sampleButton", "Sample")),

 mainPanel(
   ggvisOutput("plot"))),

 server = function(input, output) {

   sampleInput <- reactive({
     input$sampleButton
     x <- rnorm(500,0,1.5)
     data.frame(x)
   })

   gv <- reactive({
     df <- sampleInput()
     df %>% ggvis(~x) %>% 
       add_tooltip(toolTipFunc(df$x), "hover") %>% 
       layer_histograms(width=0.5) %>%
       set_options(width=540,height=350,keep_aspect=TRUE)
   })

   gv %>% bind_shiny("plot")

 }))

There was a working solution to this on the google ggvis group here . Essentially you don't need your verbose, separate tool_tip function. You can just use the following if using the default stack = TRUE

gv <- reactive({
  df <- sampleInput()
  df %>% ggvis(~x) %>% 
    layer_histograms(width=0.5) %>%
    add_tooltip(function(df){ df$stack_upr_ - df$stack_lwr_}) %>%
    set_options(width=540,height=350,keep_aspect=TRUE)
})

or if stack=FALSE

gv <- reactive({
  df <- sampleInput()
  df %>% ggvis(~x) %>% 
    layer_histograms(width=0.5, stack=FALSE) %>%
    add_tooltip(function(df){ df$count_}) %>%
    set_options(width=540,height=350,keep_aspect=TRUE)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM