悬停时突出显示一组数值

33

假设数据

library(ggplot2)
library(plotly)

set.seed(357)
xy <- data.frame(letters = rep(c("a", "b", "c"), times = 3),
                 values = runif(9),
                 groups = rep(c("group1", "group2", "group3"), each = 3))

  letters    values groups
1       a 0.9913409 group1
2       b 0.6245529 group1
3       c 0.5245744 group1
4       a 0.4601817 group2
5       b 0.2254525 group2
6       c 0.5898001 group2
7       a 0.1716801 group3
8       b 0.3195294 group3
9       c 0.8953055 group3

ggplotly(
  ggplot(xy, aes(x = letters, y = values, group = groups)) +
  theme_bw() +
  geom_point()
)

我的目标是,在鼠标悬停时,突出显示属于同一组的所有点。例如,在上右角的点上悬停时,该组(圆圈)中的所有点将变为红色。使用layout(hovermode = "x")可以实现类似的效果,但前提是只想突出显示其中一个轴上的所有点。我希望对于除了xyclosest之外的自定义变量,具有相同的行为(它们是hovermode的模式)。

输入图像描述

1个回答

32

这可能会满足你的需求

示例数据

set.seed(357)
xy <- data.frame(letters = rep(c("a", "b", "c"), times = 3),
                 values = runif(9),
                 groups = rep(c("group1", "group2", "group3"), each = 3))

绘图

#create a SharedData object for use in the ggplot below, group by 'groups' 
d <- highlight_key(xy, ~groups )

#create a normal ggplot to fit your needs, but use the SharedData object as data for the chart
p <- ggplot( d, aes(x = letters, y = values, group = groups)) + theme_bw() + geom_point()

#now ggplotly the newly created ggplot, and add text for the tooltips as needed
gg <- ggplotly( p, tooltip = "groups" )

#set the highlight-options to your liking, and plot...
highlight( gg, on = "plotly_hover", off = "plotly_deselect", color = "red" )
绘制结果

enter image description here


有没有任何想法如何使用 plot_ly() 实现这个目标。我有一个类似的问题:https://stackoverflow.com/questions/57655036/plotly-hoverinfo-for-both-points-connected-by-line-markerslines-using-grou - Claudiu Papasteri
如果您想在某个x值上为所有组(值)设置悬停文本,您会采用相同的方法吗? - mihagazvoda
你能否请看一下这个问题? https://dev59.com/N7_qa4cB1Zd3GeqPH3Nn 谢谢! - stats_noob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接