13

I'm using the Plotly python library to generate a figure with several violin plots and several filled scatter plots. No matter what order I have the individual fig.add_trace calls in my code, the violin plots always plot behind the scatter plots.

Does anyone know if there is a specific method for controlling layout or plot order? Something like zorder=3?

Scatter Plots in front of Violins

Jonathan Fry
  • 643
  • 2
  • 7
  • 13

3 Answers3

13

There's a feature request for this, and a workaround proposed that works some of the time: feature request: z-ordering parameter for traces.

import plotly.express as px
import plotly.graph_objects as go

fig = px.scatter(x=[1,2,3,4], y=[1,2,3,4], size=[1,2,3,4], color=["a","a","b","b"])
fig.add_trace(go.Scatter(x=[1,2,3,4], y=[1,2,3,4], mode="lines", line_color="black"))

# Re-order the data:
fig.data = (fig.data[1],fig.data[0])
# fig.data = fig.data[::-1]  # alternatively, via slicing

fig.show()
ptim
  • 14,902
  • 10
  • 83
  • 103
3

At the moment you can control trace order within trace types by ordering the trace objects in the data array, but not across trace types, so violins will always draw behind scatters.

nicolaskruchten
  • 26,384
  • 8
  • 83
  • 101
-2

I found a clever way around it. In this case, you first assign the graph object to a variable:

PLOT1 = go.Scatter(STUFF)
PLOT2 = go.Scatter(STUFF)
PLOT3 = go.Scatter(STUFF)

You can then specify a dictionary with the desired order:

order = {"1":PLOT3, "2":PLOT1, "3":PLOT2}

for i in np.arange(1, len(order) + 1):
    for plot_order, trace in order.items():
        if plot_order == str(i):
            fig.add_trace(trace)

This way you control the order with the dictionary. I hope it helps! It helped me.