在 ggvis 中使用 add_tooltip 在鼠标悬停时打印名称
using add_tooltip in ggvis to print name when mouse hovers
我的数据看起来像这样:
df = data.frame(name=c("A1", "A2"),
x = c(2,4),
y = c(2,5),
sector = c("blue", "red"))
我正在尝试使用 ggvis 创建图表,但无法使工具提示正常工作。
library(ggvis)
df %>%
ggvis(~x, ~y, size := 100, opacity := 0.4) %>%
layer_points(fill = ~sector) %>%
add_tooltip(function(df) df$name)
当我悬停鼠标时 df$name
没有出现。我做错了什么?
谢谢!
add_tooltip 的帮助文件有一条线索:
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.
我下面的修复改编自该帮助文件中的示例。
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")
我的数据看起来像这样:
df = data.frame(name=c("A1", "A2"),
x = c(2,4),
y = c(2,5),
sector = c("blue", "red"))
我正在尝试使用 ggvis 创建图表,但无法使工具提示正常工作。
library(ggvis)
df %>%
ggvis(~x, ~y, size := 100, opacity := 0.4) %>%
layer_points(fill = ~sector) %>%
add_tooltip(function(df) df$name)
当我悬停鼠标时 df$name
没有出现。我做错了什么?
谢谢!
add_tooltip 的帮助文件有一条线索:
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.
我下面的修复改编自该帮助文件中的示例。
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")