Skip to content Skip to sidebar Skip to footer

Plotly: How To Change The Trace Order, Or Switch The Sides Of The Axes In Plotly?

I am trying to get the line to display over the bar. It seems that whatever trace has secondary_y=True will be drawn on top of the one where secondary_y=False. That's fine, but for

Solution 1:

It's not easy providing a complete solution without a sample of your dataset, but I still think I've figured it out. I'm in a bit of a hurry right now, so I'll make it short:

Bars are big numbers, lines are small numbers. Out of the box, a fig = make_subplots(specs=[[{"secondary_y": True}]]) would provide this:

enter image description here

Line trace on top = Good. Bar numbers to the left = Bad.

Changing the order of which yoy apply the different traces to the figure won't help. But you can freely specify on which side of the plot you'd like your primary and secondary y axis to appear like this:

fig.update_layout(dict(yaxis2={'anchor': 'x', 'overlaying': 'y', 'side': 'left'},
                  yaxis={'anchor': 'x', 'domain': [0.0, 1.0], 'side':'right'}))

Add that to the mix, and you'll get:

enter image description here

Line trace on top = Good. Bar numbers to the right = Good.

Complete code with a data sample:

# importsimport plotly.graph_objects as go
import numpy as np
from plotly.subplots import make_subplots

# set figure twith multiple y axes
fig = make_subplots(specs=[[{"secondary_y": True}]])

# blue line with numbers from 1 to 3
fig.add_trace(
    go.Scatter(x=[0, 1, 2, 3, 4, 5],
               y=[1.5, 1.0, 1.3, 2.7, 1.8, 2.9]),secondary_y=True)

# red bars with big numbers
fig.add_trace(
    go.Bar(x=[0, 1, 2, 3, 4, 5],
           y=[np.nan, np.nan, np.nan, 100000, 20000, 250000]))

# update layout to put axes and values in the desired positions
fig.update_layout(dict(yaxis2={'anchor': 'x', 'overlaying': 'y', 'side': 'left'},
                  yaxis={'anchor': 'x', 'domain': [0.0, 1.0], 'side':'right'}))

fig.show()

Post a Comment for "Plotly: How To Change The Trace Order, Or Switch The Sides Of The Axes In Plotly?"