Search code examples
rplotlyr-plotly

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


Dataframe:

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

And this is the code to generate the pie chart:

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

Basically, I would like to highlight the label that I'm hovering over and grey out the other labels, like these plots: 1st plot and 2nd plot.

Is there a way to do this?


Solution

  • I used a gray and default color array and used the point you hover on as a replacer in the array of all gray colors, then it's sent to the graph as a plotly_restyle. If you're familiar with how updatemenus works for buttons, it's essentially the same coding, just in JS instead of 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
    

    enter image description here