r - 突出显示悬停时组中的所有值

标签 r ggplot2 plotly ggplotly

假设数据

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的模式)以外的自定义变量的相同行为。

enter image description here

最佳答案

这可能会满足您的需求

样本数据

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

关于r - 突出显示悬停时组中的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52532428/

相关文章:

r - 通过渐变颜色 R plotly 文本注释

r 中带有重叠圆圈(填充和大小)的行列热图

r - 更改颜色中线 ggplot geom_boxplot()

angular - 如何在 Angular 2+ 包装器中向 plotly.js 添加数据点

r - 通过 Shiny 中的串扰将 Plotly 与 DT 结合使用

r - 当需要 "size"美学和 geom_smooth 时更改图异常(exception)观

r - 我可以计算行或列的最小值或最大值,也可以计算列的平均值,但无法计算行的平均值。为什么不?

r - 在 R 中的 ggplot 密度曲线的小平面包裹下使用渐变填充?

r - 在 ggforce::geom_parallel_sets 上对 y 轴排序

r - 条形图 R 中的颜色