Dana_Miles
Dana_Miles

Reputation: 429

Continuous color scales for markers in Plotly boxplot

How to add continuous colors to the markers of a boxplot? I would like them to go from white (at 0) to dark green (max positive value) and white to dark red for max negative value.

To avoid white markers in front of the boxplot - how to put the boxplot on top of the markers?

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

Upvotes: 2

Views: 2450

Answers (1)

Derek O
Derek O

Reputation: 19610

I think the best method would be to use one trace to create the boxplot, and another trace to create a scatterplot of the points. You have more parameters you can set in a scatterplot, and you can also set the colorscale of the marker in a dictionary: by passing an array with 0 mapped to dark red, 0.5 mapped to transparent grey (opacity = 0), and 1 mapped to dark green.

Since the boxplot is categorical, and you passed the parameter name='Markers', if we set the y values of the scatterplot to 'Markers' the scatterplot of the points will be superimposed on top of the boxplot. Also, as an aside, it's a good idea to set a seed to ensure reproducibility.

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

enter image description here

Upvotes: 1

Related Questions