Search code examples
rggvis

Possible bug for tooltip in ggivs?


The code below doesn't work as it should, which is that when the pointer is hovering over a point, it should show the Num...

iris$Sepal.Length.j <- jitter(iris$Sepal.Length)
iris$Sepal.Width.j <- jitter(iris$Sepal.Width)
iris$Num <- 1:nrow(iris)
iris %>% group_by(Species) %>% 
  ggvis(~Sepal.Length.j, ~Sepal.Width.j, opacity:=0.5) %>% 
  layer_points(fill=~Species) %>% layer_smooths(stroke=~Species) %>%
  add_tooltip(html=function(x) {
    if (!is.list(x)) return()
    x$Num}, on="hover")

Is this a possible bug or am I misunderstood? The code below works fine.

iris %>% group_by(Species) %>% 
  ggvis(~Sepal.Length.j, ~Sepal.Width.j, opacity:=0.5) %>% 
  layer_points(fill=~Species) %>% layer_smooths(stroke=~Species) %>%
  add_tooltip(html=function(x) {
    if (!is.list(x)) return()
    x$Sepal.Width}, on="hover")

Solution

  • There are a couple of things going on here. First is about the data columns that ggvis uses.

    From the "Examples" section of the add_tooltip help page:

    The data sent from client to the server contains only the data columns that are used in the plot. If you want to get other columns of data, you should to use a key to line up the item from the plot with a row in the data.

    In your second plot, Sepal.Width was used in the plot and so was available for the tooltip. But you never used Num in the plotting code so it wasn't available to be used in the tooltip. To keep Num in the data columns for the plot, you need to indicate that this is your key column.

    That's an easy fix - just add key := ~Num to layer_points.

    There are some other subtle issues with grouping and tooltips, some of which are outlined in this answer. In your case, if you group after layer_points and before layer_smooth I think the tooltip works as you would like it to.

    So your code could look like:

    iris %>%
        ggvis(~Sepal.Length.j, ~Sepal.Width.j, opacity:=0.5) %>% 
        layer_points(fill=~Species, key := ~Num) %>% 
        group_by(Species) %>%
        layer_smooths(stroke=~Species) %>%
        add_tooltip(html=function(x) {
            if (!is.list(x)) return()
            x$Num}, on="hover")