在 R plotly scattergl 中设置动态 hoverlabel 背景颜色

Set dynamic hoverlabel background color in R plotly scattergl

当使用 scattergl 而不是 scatter 时,R plotly 中的动态 hoverlabel 背景颜色似乎不起作用,如下例所示。

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"))))

type = "scattergl":

的所有数据点的 hoverlabel 背景颜色变为黑色
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"))))

我想一个解决方案是通过 hoverlabel = list(bgcolor = ???)colorscale 中使用的相同颜色数组传递给 bgcolor 参数。但是我不知道该怎么做。


编辑
根据@Quinten 的回答进行了尝试,但没有成功。可以看出,颜色是默认的 plot_ly 颜色,与 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()

您可以使用 RColorBrewer 创建 6 种不同颜色的矢量。您分配给 markercolorhoverlabelbgcolor 的这些颜色将显示正确的颜色。您可以使用以下代码:

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))

输出:

从图中可以看出,标签与标记的颜色相同。