Hover background color on scatter 3d

@umberto.lupo

A workaround is to define a function that maps a value in an interval [vmin,vmax] to the corresponding color in a plotly colorscale.

Below is defined a function for Plotly colorscales with rgb color codes. A few lines must be added for hex colors:

from plotly.colors import * #https://github.com/plotly/plotly.py/tree/master/packages/python/plotly/_plotly_utils/colors

from ast import literal_eval
import numpy as np

def get_color_for_val(val, vmin, vmax, pl_colors):
    
    if pl_colors[0][:3] != 'rgb':
        raise ValueError('This function works only with Plotly  rgb-colorscales')
    # to do: add lines for hex to rgb   
    if vmin >= vmax:
        raise ValueError('vmin should be < vmax')
    
    scale = [k/(len(pl_colors)-1) for k in range(len(pl_colors))] 
    colors_01 = np.array([literal_eval(color[3:]) for color in pl_colors])/255.  #color codes in [0,1]
    v= (val - vmin) / (vmax - vmin) # val is mapped to v in [0,1]
    #find two consecutive values in plotly_scale such that   v is in  the corresponding interval
    idx = 1
    while(v > scale[idx]): #sequential searching of the interval
        idx += 1
    vv = (v - scale[idx-1]) / (scale[idx] -scale[idx-1] )
    
    #get   [0,1]-valued color code representing the rgb color corresponding to val
    val_color01 = colors_01[idx-1] + vv * (colors_01[idx ] - colors_01[idx-1])
    val_color_0255 = (255*val_color01+0.5).astype(int)
    return f'rgb{tuple(val_color_0255)}'

#####################
import plotly.graph_objects as go

pl_colors =  cmocean.deep[::-1]  #define the deep colorscale
np.random.seed(123)
color_vals= 1+4*np.random.rand(20)
vmin= color_vals.min()
vmax=color_vals.max()
bgcolor = [get_color_for_val(v, vmin,vmax,pl_colors) for v in color_vals]

fig= go.Figure(go.Scatter3d(x=np.random.randint(2, 10, 20), 
                            y=np.random.randint(2, 10, 20),
                            z=np.random.randint(2, 10, 20),
                            mode='markers', marker_size=8,
                            marker_color=color_vals,
                            marker_colorscale='deep_r',
                            text =list(range(20)),
                            hoverinfo='text',
                            hoverlabel_bgcolor=bgcolor))
1 Like