在 ggvis 中悬停使用 add_tooltip 时从显示信息中排除 line/points

Exclude line/points from showing info when using add_tooltip with hover in ggvis

我一直在研究这个不错的 ggvis 包。我正在做一个自定义线性回归并想要一个工具提示来显示有关每个数据点的信息。但是,当我添加回归线时,当我将鼠标悬停在该线上时会出现工具提示,然后显示有关第一个数据点的信息(参见屏幕截图)。我提供了这个简单的可重现示例:

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

这产生了这个

我想从工具提示中排除回归线,因此它只显示有关数据点的信息。有没有办法做到这一点?谢谢您的帮助!

经过一番尝试后,我开始使用它了。

首先,我需要构建两个独立的数据集才能使其正常工作。一种用于线性模型数据,一种用于 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 上时,将从 mtc 访问 id 列,而每当您将鼠标悬停在 all_values 线上时,将从 df 访问 id 列。

我在下面的函数中添加了一行,这就是它起作用的原因:

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

然后绘制两个单独的 data.frames。 add_tooltip 将为两个 data.frame 找到 id 变量:

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

我无法显示与此图表的完整交互性,但您可以在下图中看到,尽管我的光标位于该行上方,但未显示任何信息。

而这些点在悬停时会显示信息。