Plotly boxplot 中标记的连续色标

Continuous color scales for markers in Plotly boxplot

如何向箱线图的标记添加连续颜色?我希望它们从白色(0)变为深绿色(最大正值),从白色变为深红色以获得最大负值。

为了避免箱线图前面出现白色标记 - 如何将箱线图放在标记之上?

import random
import numpy as np 
import plotly.graph_objects as go

rand = np.random.uniform(-100, 100, 100)

fig = go.Figure()
fig.add_trace(go.Box(
    x=rand,
    name='Markers',
    showlegend=True,
    jitter=0,
    pointpos=0,
    boxpoints='all',
    marker_color='rgba(7, 40, 89)',
    marker_size=14,
    marker_opacity=1,
    line_color='rgba(128, 128, 128, .0)',
    fillcolor='rgba(128, 128, 128, .3)',
))
fig.update_layout(template='plotly_white')
fig.show()

我认为最好的方法是使用一条轨迹创建箱线图,使用另一条轨迹创建点的散点图。您可以在散点图中设置更多参数,还可以在字典中设置标记的 colorscale:通过传递一个数组,其中 0 映射到深红色,0.5 映射到透明灰色(不透明度 = 0) , 和 1 映射到深绿色。

由于箱线图是分类的,并且您传递了参数 name='Markers',如果我们将散点图的 y 值设置为 'Markers',则点的散点图将叠加在箱线图的顶部.另外,顺便说一句,设置种子以确保可重复性是个好主意。

import random
import numpy as np 
import plotly.graph_objects as go

np.random.seed(42)
rand = np.random.uniform(-100, 100, 100)

fig = go.Figure()
fig.add_trace(go.Box(
    x=rand,
    name='Markers',
    showlegend=True,
    jitter=0,
    pointpos=0,
    line_color='rgba(128, 128, 128, .0)',
    fillcolor='rgba(128, 128, 128, .3)',
))

## add the go.Scatter separately from go.Box so we can adjust more marker parameters
## the colorscale parameter goes from 0 to 1, but will scale with your range of -100 to 100
## the midpoint is 0.5 which can be grey (to match your boxplot) and have an opacity of 0 so it's transparent
fig.add_trace(go.Scatter(
    x=rand,
    y=['Markers']*len(rand),
    name='Markers',
    mode="markers",
    marker=dict(
        size=16,
        cmax=100,
        cmin=-100,
        color=rand,
        colorscale=[[0, 'rgba(214, 39, 40, 0.85)'],   
               [0.5, 'rgba(128, 128, 128, 0)'],  
               [1, 'rgba(6,54,21, 0.85)']],
    ),
    showlegend=False
)).data[0]
fig.update_layout(template='plotly_white')
fig.show()