绘图上的自定义悬停比较将根据类别而不是 x 或 y 突出显示?

问题描述 投票:0回答:1

我问这个问题是作为上一个问题的延伸。好奇心让我想知道是否可以修改悬停模式,以便在堆叠百分比图表中,它将突出显示相同颜色的所有分段的百分比值,每个条形中一个。本质上是普通图表中的“x”悬停模式。但由于我们将不同的值堆叠在一起,默认的 x 模式似乎并不直观地以这种方式工作。

这是我的代码。任何帮助将不胜感激。

dat <- data.frame(group1=(rep(letters[1:4], each=5)), 
           group2=rep(LETTERS[1:5], times=4),
           pct = c(rep(.2, times=5), 
                   c(.1, .1, .1, .3, .4), 
                   c(.2, .2, .2, .3, .1),
                   c(.3, .1, .2, .2, .2))
           )
dat %>%
  plot_ly() %>%
  add_bars(x=~pct, y=~group1,  color=~group2,
           customdata = ~group2,
           hovertemplate = paste0(
             "%{y:.2f%}<br>",
             "<extra>%{customdata}</extra>"
             )
           ) %>% 
      layout(yaxis = list(title = 'Group 1', 
                          autorange='reversed', 
                          categoryorder='trace'),
             xaxis = list(title = 'Percent', tickformat = ".0%"),
             barmode = 'stack', 
             hovermode = 'y',

             legend = list(traceorder = "normal")) %>%
      config(displaylogo = FALSE
             #,modeBarButtonsToRemove = list('hoverCompareCartesian'
             )
r plotly stacked-bar-chart
1个回答
0
投票

这是一个使用自定义事件处理程序的选项:

library(plotly)

dat %>%
  plot_ly() %>%
  add_bars(
    x = ~pct, y = ~group1, color = ~group2,
    customdata = ~group2,
    hovertemplate = paste0(
      "%{x:.0%}<br>%{y}<extra>%{customdata}</extra>"
    )
  ) %>%
  layout(
    yaxis = list(
      title = "Group 1",
      autorange = "reversed",
      categoryorder = "trace"
    ),
    xaxis = list(title = "Percent", tickformat = ".0%"),
    barmode = "stack",
    legend = list(traceorder = "normal")
  ) %>%
  config(
    displaylogo = FALSE
  ) |>
  htmlwidgets::onRender(
    "function(el, x){el.on('plotly_hover', function(d) {
      var points = d.points[0];
      var pointNum = points.pointNumber;
      var curveNumber = points.curveNumber;
      Plotly.Fx.hover(el.id, [
          { curveNumber: curveNumber, pointNumber: 0 },
          { curveNumber: curveNumber, pointNumber: 1 },
          { curveNumber: curveNumber, pointNumber: 2 },
          { curveNumber: curveNumber, pointNumber: 3 }],
        );
    })}"
  )

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.