ggivs 中工具提示的可能错误?

Possible bug for tooltip in ggivs?

下面的代码无法正常工作, 也就是当指针悬停在一个点上时, 它应该显示 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")

这可能是错误还是我误解了? 下面的代码工作正常。

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

您的绘图的输入数据集中没有名为 "Num" 的列 - 这就是它不起作用的原因。您的第二个示例有效,因为 "Sepal.Width" 是 iris 数据中的一列。

这里发生了几件事。首先是关于 ggvis 使用的数据列。

来自 add_tooltip 帮助页面的 "Examples" 部分:

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.

在您的第二个绘图中,绘图中使用了 Sepal.Width,因此可用于工具提示。但是您从未在绘图代码中使用过 Num,因此无法在工具提示中使用它。要在绘图的数据列中保留 Num,您需要指明这是您的 key 列。

这很容易解决 - 只需将 key := ~Num 添加到 layer_points

分组和工具提示还有其他一些微妙的问题,this answer 中概述了其中一些问题。在您的情况下,如果您在 layer_points 之后和 layer_smooth 之前分组,我认为工具提示会按照您的意愿工作。

因此您的代码可能如下所示:

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