Bring Drag & Drop to Dash with Dashboard Engine. 💫 Learn how at our next webinar!

Send trace to background without changing the colors of the other traces

I have the following data:

import numpy as np
from scipy import stats
import plotly.graph_objects as go
# Simlate Random Walk
N = 100 
xs = np.arange(N)

X = np.zeros(N)
for i in range(1, N):
    X[i] = X[i-1] + np.random.normal(scale=1)
    
# Measurements
Y = X + np.random.normal(scale=1, size=N)

# Moving average over the measurements
Z = np.column_stack([Y[:-3],Y[3:]]).mean(axis=1)

# Quantiles
lower, upper = stats.norm.ppf([.025, .975], loc=Z[:,None], scale=1).T

Plotting:

fig = go.Figure()
fig.add_scatter(x=xs, y=X)
fig.add_scatter(x=xs, y=Y, mode='markers')
fig.add_scatter(x=xs[3:], y=Z, line_shape='spline')
fig.add_scatter(x=np.concatenate([xs[3:],xs[3:][::-1]]), y=np.concatenate([lower, upper[::-1]]), 
                fill='toself', line_width=0)
fig.layout.update(height=600, showlegend=False)
fig.show()

The filling covers the other plots, I want to send it to the background, that is, as if it were the first trace to be added without changing the colors of any of the traces.
If I were to simply add this trace first, all my feng shui would be distorted, colors will no longer correspond to those already used to create previous plots.

Some solutions would be:

  • always use my own colors. A pity, I like the ones plotly provides but I cannot retrieve them.
    (Related to: Get color of a trace)

  • keep the colors as they are, but change the order of traces. This I do not know how to do and is the subject of this question.

Another motivation, is that I want to be able to hover over some of the covered traces.
I have asked here about that:

I’m glad you like plotly’s colors :-). As you were suggesting, you can control the order in which you add the traces, and set your colors to the ones used by plotly. A list was given in this post Plotly colours list (and we should make sure it appears in the doc as well :-)). Hope this helps!

1 Like

Thank you! For my case, the list of colors is here.