突出显示悬停时组中的所有值 [英] Highlight all values from a group on hover

查看:97
本文介绍了突出显示悬停时组中的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设数据

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的模式)以外的自定义变量,我希望具有相同的行为.

My goal is to, on hover, highlight all points that belong to the same group. E.g. on hover over the point in the upper right corner, all points from this group (circles) would turn red. Something similar can be achieved using layout(hovermode = "x") but only if one is interested in highlighting all points on one of the axes. I would like the same behavior for custom variable other than x, y or closest (which are modes of hovermode).

推荐答案

这可能会满足您的需求

样本数据

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

绘制结果

这篇关于突出显示悬停时组中的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆