Search code examples
rggvis

aggregating functions in ggvis add_tooltip


I am trying to add the frequency of each bar into a tooltip and am having issues. I attempted to use a group_by unsuccessfully. The tooltip returns a 4 for each tooltip for each bar.

mtcars %>%
  ggvis(x = ~cyl) %>%
  layer_histograms(fill="sky blue"
                   , fillOpacity:=.7
                   , fillOpacity.hover:=.9) %>%
  group_by(cyl) %>%
  add_tooltip(function(x) length(x))

This method has the same issue. It returns a 4 for each bar...

Freq <- function(x) {
  paste0("Frequency: ", length(x))
}

mtcars %>%
  ggvis(x = ~cyl) %>%
  layer_histograms(fill="sky blue"
                   , fillOpacity:=.7
                   , fillOpacity.hover:=.9) %>%
  group_by(cyl) %>%
  add_tooltip(Freq)

Solution

  • To just quickly enable tool-tips with all values you can create a function all_values and add those.

    all_values <- function(x) {
      if(is.null(x)) return(NULL)
      paste0(names(x), ": ", format(x), collapse = "<br />")
    }
    mtcars %>% group_by(cyl) %>%
      ggvis(x = ~cyl) %>%
      layer_histograms(fill="sky blue"
                       , fillOpacity:=.7
                       , fillOpacity.hover:=.9) %>%
      add_tooltip(all_values, "hover")
    

    You can use that information to piece together a function for what you actually want to show. In this case, just the upper value of the piece of the stacked bar chart.

    mtcars %>% group_by(cyl) %>%
      ggvis(x = ~cyl) %>%
      layer_histograms(fill="sky blue"
                       , fillOpacity:=.7
                       , fillOpacity.hover:=.9) %>%
      add_tooltip(function(df) (df$stack_upr_),"hover")