Bertil Johannes Ipsen
Bertil Johannes Ipsen

Reputation: 1766

Plotly Express: Order of elements in plot (python)

When using Plotly Express, the easiest way to add multiple traces seems to be the "Add Trace Convenience Methods", such as fig.add_scatter. My problems is that when using this method, it seems to me like there is no way to to force this added trace to the top of the drawing.

The following example code produces a graph where the red "trace 1" markers are hidden behind the blue markers created using Plotly Express. How could one go about putting this layer on top of the draw order? I have tried messing around with the stackgroup parameter, but this had no effect.

import numpy as np
import plotly.express as px

fig = px.scatter(x=np.random.rand(20000), y=np.random.rand(20000))

fig.add_scatter(x=np.random.rand(5), y=np.random.rand(5),
                mode='markers', marker=dict(size=40))

fig.show()

Example Plotly graph

Upvotes: 1

Views: 4091

Answers (1)

Harm
Harm

Reputation: 665

Not in Plotly Express, because that doesn't support multiple axes, but:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

# Create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])

fig.add_trace(
    go.Scatter(x=np.random.rand(20000), y=np.random.rand(20000)),
    secondary_y=False
)

fig.add_trace(
    go.Scatter(x=np.random.rand(5), y=np.random.rand(5),
               mode='markers', marker=dict(size=40)),
    secondary_y=True
)

fig.show()

plotly-express-order-of-elements-in-plot-python

You might then need to align both axes as explained here.

Upvotes: 1

Related Questions