'Set dynamic hoverlabel background color in R plotly scattergl

The dynamic hoverlabel background color in R plotly does not seem to work when using scattergl instead of scatter as depicted in the example below.

Works as intended with type = "scatter":

library(plotly)

X <- data.frame(x = 1:6,
                y = 1:6,
                z  = 1:6)

plot_ly(data = X, x = ~x, y = ~y,
        type = "scatter", mode = "markers",
        marker = list(color = ~x, 
                      colorscale = list(c(0, .5, 1), c('#0d71db', "#dbc00d", "#db220d"))))

enter image description here

The hoverlabel background color becomes black for all data points with type = "scattergl":

plot_ly(data = X, x = ~x, y = ~y,
        type = "scattergl", mode = "markers",
        marker = list(color = ~x, 
                      colorscale = list(c(0, .5, 1), c('#0d71db', "#dbc00d", "#db220d"))))

enter image description here

I guess a solution could be to pass the same color array used in colorscale to the bgcolor argument via hoverlabel = list(bgcolor = ???). However I have no idea how to do so.


Edit
Tried this based on @Quinten's answer, without success. As can be seen the colors are the default plot_ly colors and do not correspond to what is specified in cols.

library(plotly)

n <- 5000
X <- data.frame(x = sample(1:100, n, replace = TRUE),
                y = sample(1:100, n, replace = TRUE),
                z = sample(1:500, n, replace = TRUE))

length_unique_vals <- length(unique(X$z))
cols <- colorRampPalette(c('#0d71db', "#dbc00d", "#db220d"))(length_unique_vals)
cols <- cols[factor(X$z)]

plot_ly(data = X, x = ~x, y = ~y,
        type = "scattergl", mode = "markers",
        marker = list(color = ~z,
                      colorscale = cols,
                      colorbar = list(title = "Colorbar")),
        hoverlabel = list(bgcolor = cols)) %>% 
  toWebGL()


Solution 1:[1]

You can create a vector of 6 different colors using RColorBrewer. These colors you assign to the color of your marker and to the bgcolor of your hoverlabel which will show the right color. You can use the following code:

library(plotly)

X <- data.frame(x = 1:6,
                y = 1:6,
                z  = 1:6)

library(RColorBrewer)
cols <- brewer.pal(n = 6, name = "Set3")

plot_ly(data = X, x = ~x, y = ~y,
        type = "scattergl", mode = "markers",
        marker = list(color = cols), 
        hoverlabel = list(bgcolor = cols))

Output:

enter image description here

As you can see from the plot, the label is the same color as the marker.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quinten