简体   繁体   中英

Change background of group label in plotly R hoverlabel

Is there a way to change the background color of the group label in plotly R? I can see that the main label can be styled but cannot find any solutions for the group label, preferably background color and font color if possible. 在此处输入图像描述

I don't know of a native Plotly method, but I can give you a workaround.

Right now, the default is to have a white background at 80% opacity.

You didn't make your question reproducible (which will typically get you great answers much faster), so I created some.

library(plotly)
library(tidyverse)

df <- data.frame(
  x = LETTERS[1:3],
  y = c(1:3)
)

I created this little chunk to replace the background color with a color of your choice...where I've currently set colr to #444 .

# current background of the trace label is white at .8 opacity
colr = "#444"  # this is the current text color in the tooltip data

plot_ly(df, x = ~x, y = ~y, name = "trace", type = 'bar',
        showlegend = T, color = ~x) %>% 
  htmlwidgets::onRender(
    paste0(
      "function(el, x) {
      colr = '", colr, "';
      el.on('plotly_hover', function(d){
      hd = document.querySelector('g.hoverlayer');
      hd.innerHTML = hd.innerHTML.replace('rgb(255, 255, 255)', colr);
    });
    }"
  ))

在此处输入图像描述

If you changed it to: colr = 'black'

在此处输入图像描述

Although, it's probably more proper to change the color this way (this does the same exact thing). One of the two may be faster if you have a lot of data, though.

plot_ly(df, x = ~x, y = ~y, name = "trace",
        showlegend = T, color = ~x, type = "bar") %>% 
  htmlwidgets::onRender(
    paste0(
      "function(el, x) {
      el.on('plotly_hover', function(d){
        hd = document.querySelector('g.hoverlayer');
        if(hd.innerHTML !== '') { /* if there's a tooltip then... */
          rct = document.querySelector('g.hoverlayer rect');
          rct.style.fill = '", colr, "';
        }
      });
      }"
    ))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM