Search code examples
rggvis

using add_tooltip in ggvis to print name when mouse hovers


My data looks something like this:

df = data.frame(name=c("A1", "A2"),
                x = c(2,4),
                y = c(2,5),
                sector = c("blue", "red"))

I am trying to use ggvis to create a graph but I am not able to make the tooltip work.

library(ggvis)
df %>% 
  ggvis(~x, ~y, size := 100, opacity := 0.4) %>% 
  layer_points(fill = ~sector) %>%
  add_tooltip(function(df) df$name)

When I hover the mouse df$name does not appear. What am I doing wrong?

Thanks!


Solution

  • The helpfile for add_tooltip has a clue:

    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.

    My fix below adapts the example from that helpfile.

    library(ggvis)
    
    df = data.frame(name=c("A1", "A2"),
                    x = c(2,4),
                    y = c(2,5),
                    sector = c("blue", "red"))
    
    # Add a unique id column
    df$id <- 1:nrow(df)
    
    # Define a tooltip function, which grabs the data from the original df, not the plot
    tt <- function(x) {
       if(is.null(x)) return(NULL)
    
       # match the id from the plot to that in the original df
       row <- df[df$id == x$id, ]   
       return(row$name)
    }
    
    
    # in the definition of the plot we include a key, mapped to our id variable
    df %>% 
       ggvis(~x, ~y, key := ~id, size := 100, opacity := 0.4) %>% 
       layer_points(fill = ~sector) %>%
       add_tooltip(tt, "hover")