Plotly R:突出显示饼图中悬停的标签并将其他标签变灰

Plotly R: highlight the hovered label in pie chart and grey out the other labels

数据框:

df2 = data.frame(value = c(9, 2, 7, 3, 6),
                 key = c('ar', 'or', 'br', 'gt', 'ko'))

这是生成饼图的代码:

df2 %>% 
  plot_ly(labels = ~key,
          values = ~value,
          type = 'pie')

基本上,我想突出显示我悬停的标签并使其他标签变灰,例如这些图:1st plot and 2nd plot.

有办法吗?

我使用了一个灰色和默认颜色数组,并使用你悬停的点作为所有灰色数组中的替代品,然后它作为 plotly_restyle 发送到图表。如果您熟悉 updatemenus 按钮的工作原理,它本质上是相同的编码,只是用 JS 而不是 R。

library(htmlwidgets)
library(plotly)

df2 = data.frame(value = c(9, 2, 7, 3, 6),
                 key = c('ar', 'or', 'br', 'gt', 'ko'))


hoverer = "function(el, x) {
            el.on('plotly_hover', function(d){
              var pn;
              var oCol = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd'];
              var nCol = ['gray','gray','gray','gray','gray'];
              pn = d.points[0].pointNumber;
              nCol[pn] = oCol[pn];
              var update = {marker:{colors: nCol}};
              Plotly.restyle(el.id, update);
            });
            el.on('plotly_unhover', function(d){
              var oCol = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd'];
              var update = {marker:{colors: oCol}};
              Plotly.restyle(el.id, update);
            });}"


df2 %>% 
  plot_ly(labels = ~key,
          values = ~value,
          # default colors; matches JS
          marker = list(colors = list('#1f77b4',  # muted blue
                                      '#ff7f0e',  # safety orange
                                      '#2ca02c',  # cooked asparagus green
                                      '#d62728',  # brick red
                                      '#9467bd')),# muted purple))
          type = 'pie') %>% onRender(hoverer) # this is from htmlwidgets library