如何在 ggplotly 对象中自定义悬停信息?

How to customize hover information in ggplotly object?

有没有办法在 ggplotly 对象中自定义 hoverinfo?

例如,

p <- ggplot(mtcars, aes(x = disp, y= am, color = as.factor(cyl)))+geom_point()

ggplotly(p)

这里的悬停信息框包含三个variables:disp,am和factor(cyl)。如何在悬停信息框中包含更多变量或排除现有变量?

谢谢!

您可以在 aes() 中包含所需的变量,然后使用 tooltip 指定应显示的变量:

p <- ggplot(mtcars, aes(x = disp, y= am, color = as.factor(cyl), 
                        gear=gear, hp=hp))+geom_point()
ggplotly(p,tooltip = c("x", "gear", "hp"))

一种更简洁的方法是只添加 ggplot 环境中的所有内容,使用美学两次,以便将完整的单个对象传递到 ggplotly():

p <- ggplot(mtcars, aes(label = gear, label2 = hp)) + 
     geom_point(aes(x = disp, y= am, color = as.factor(cyl)))

ggplotly(p)