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)
})