Y Axis alignment with different range

Hello,

I would like to plot two lines on the same graph using different y-axes. Both lines have very different ranges. This is important because I have seen recommendations to use a common range for the axes.

Below is a reproducible example:

import plotly.graph_objects as go

fig = go.Figure()

# First line with primary y-axis
fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4],
    y=[-10, 11, 12, 13],
    mode='lines',
    name='Line 1',
    line=dict(color='red')
))

# Second line with secondary y-axis
fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4],
    y=[-20, 122, 204, 260],
    mode='lines',
    name='Line 2',
    yaxis='y2'
))

# Create axis objects
fig.update_layout(
    yaxis=dict(title='Primary Y-axis', zeroline=True, zerolinewidth=2),
    yaxis2=dict(title='Secondary Y-axis', overlaying='y', side='right', zeroline=True, zerolinewidth=2)
)

fig.show()

In that example, the zeros of the y-axes aren’t aligned, which makes the graph harder to read.

Many thanks in advance for your time and help :slight_smile:

As far as I know, the ability to synchronize the scale values of the second axis has been added, but it does not seem to go as far as synchronizing the zero point. A manual workaround is to set the maximum positive value of the scale range as the maximum negative value so that the scale of the second axis is centered on the zero point. Then manually adjust the negative value by adjusting the zero point. In my environment, range=[-214,270] looks best.

    yaxis2=dict(
        title='Secondary Y-axis',
        overlaying='y',
        side='right',
        zeroline=True,
        zerolinewidth=2,
        range=[-214,270],
    )

Thanks for your reply.
It was one of my original idea, but this plot is part of a more complex project and manually changing the range isn’t possible.

I hope synchronizing the zeroes (or any value) is added in the future :crossed_fingers:

1 Like