Align two y axes with negative values

Hi! Is it possible to align the zeroes of the axes of a barplot and scatterplot which have negative values? rangemode = ‘tozero’ is doing what I need, but it does not work with negative values. Here is a sample code

import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame({'var_1': [8, 8, 16], 'var_2': [5, 10, 8], 'var_3': [1, 2, 3]})

fig = make_subplots(specs=[[{"secondary_y": True}]])

fig.add_trace(
    go.Bar(x=df.var_3, y=df.var_1 - df.var_2), secondary_y = False
)

fig.add_trace(
    go.Scatter(x=df.var_3, y=(df.var_1 - df.var_2)/df.var_2), secondary_y = True
)

fig['layout']['yaxis2']['showgrid'] = False
fig

The first screenshot is the output of the code and the second is what I’m trying to achieve.
(I manually dragged the right axis on the second screenshot.)


Hi @MartinLazarv

I am a Dash Newbie and might be getting the wrong end of the stick, but are you able to set the same range somehow for both subplots to ensure they line up?

e.g. in my streaming chart, I constantly update the y range to ensure my share price does not fall off the plot…

go.Layout(yaxis={‘range’: [min(tick_list) * 0.9994, max(tick_list) * 1.0006]})

1 Like

Thanks for your answer @umernalla !
Indeed I had to adjust the ranges, but unfortunately it was not that simple. I went through a several posts from other people on this topic and the only thing that worked was this rather long, but well explained solution here:


I hope that this will be integrated into the plotly libraries in the future so it wouldn’t be necessary to go through all the steps manually.