Exclude line / dots from displaying information when using add_tooltip with hang in ggvis

I played with the beautiful ggvis package. I am doing a custom linear regression and wanted a tooltip to show information about each data point. However, when I add my regression line, a tooltip appears when I hover over the line, and then shows information about the first datapoint (see screenshot). I provide this simple reproducible example:

library(ggvis)
mtc <- mtcars
lm=with(mtc,lm(mpg~wt))
mtc$fit=lm$coefficients[1]+mtcars$wt*lm$coefficients[2]
mtc$id <- 1:nrow(mtc)  # Add an id column to use ask the key

all_values <- function(x) {
    if(is.null(x)) return(NULL)
    row <- mtc[mtc$id == x$id, ]
    paste0(names(row), ": ", format(row), collapse = "
           ")
}

mtc %>% ggvis(x = ~wt, y = ~mpg, key := ~id) %>%
    layer_points() %>%layer_lines(x= ~wt,y= ~fit)%>% 
    add_tooltip(all_values, "hover")

It creates enter image description here

I would like to exclude the regression line from the tooltip so that it only displays information about data points. Is there any way to achieve this? Thanks for the help!

+4
source share
1 answer

After a short conversation, I made it work.

. mtcars.

mtc <- mtcars
mtc$id <- 1:nrow(mtc) 

lm=with(mtc,lm(mpg~wt))
df=data.frame(fit=lm$coefficients[1]+mtcars$wt*lm$coefficients[2])
df$id <- 101:132
df$wt <- mtcars$wt

, mtc - mtcars, df - . , df id, 100, mtc data.frame.

, all_values, id mtc, , all_values, id df.

, :

all_values <- function(x) {
  #if the id is greater than 100 i.e. the df data.frame
  #then return NULL
  if(x$id>100) return(NULL)
  if(is.null(x)) return(NULL)
  row <- mtc[mtc$id == x$id, ]
  paste0(names(row), ": ", format(row), collapse = "
           ")
}

. add_tooltip id data.frames:

ggvis(x=~wt) %>%
     layer_points(data=mtc, y = ~mpg, key := ~id) %>%
     layer_paths(data=df,y= ~fit, key := ~id) %>%
     add_tooltip(all_values, "hover")

, , , .

enter image description here

.

enter image description here

+3

All Articles