Change traces order

Hello i am new using plotly and I have a question

I am plotting a scatter and a regression line but the points of the scatter cover the line, i want the line to be on top but i don’t know how. Here is my code for the plot:

scatter_plot = px.scatter(dfpanda, x=“index”, y=‘MoistureSensorRawAdc’,title=“MoistureSensorRawAdc”)
regression_trace = go.Scatter(x=dfpanda[‘index’], y=ypred, name=‘Regression Line’, line=dict(color=‘firebrick’))

fig = go.Figure()
fig.add_traces(scatter_plot.data)
fig.add_traces(regression_trace)
fig.update_traces(showlegend=True)
fig.update_layout(
title=‘MoistureSensorRawAdc con Linea de Regresion’,
xaxis_title=‘Index’,
yaxis_title=‘MoistureSensorRawAdc’,

)
And this is how it looks:

Hi @PirateKing Welcome to the forums.

I think you can do so with the latest release of plotly. Check the release notes. I remember reading about it.

If you use go.Scatter() instead of px.Scatter() for the first plot they display in the right order.
e.g. this simplified example:

import plotly.graph_objects as go
import random

x = [random.uniform(0., 2.) for _ in range(20000)]
y = [xval + random.uniform(-1., 1.) for xval in x]
ypred= x

scatter_plot = go.Scatter(x=x, y=y, mode="markers")
regression_trace = go.Scatter(x=x, y=ypred, 
                             line=dict(color='firebrick'))

fig = go.Figure()
fig.add_traces(scatter_plot)
fig.add_traces(regression_trace)
fig.show()

There’s further discussion of this at:

2 Likes

Look for zorder in this thread

2 Likes

Yes, this is better than my suggestion - simpler, and setting zorder>0 on a trace generated by go does position it in front of traces generated by px.