How to align two y-axes when using the range parameter?

Joined
Jun 1, 2023
Messages
1
Reaction score
0

I have the plot as you can see above. Now I want to add a range to the yaxis and yaxis2, but when I do this the bar and line in my plot doesn't allign anymore like the plot above. How to fix this so the bar and line will allign? See the code below with the range parameter in it (so the code of the plot above is without the range parameter and is correct):

import plotly.graph_objects as go

bar_trace = go.Bar(x=line_s['Year/Quarter'], y=line_s['test1'], name='test1')

line_trace1 = go.Scatter(x=line_s['Year/Quarter'], y=line_s['test2'],
name='test2', yaxis='y2', mode='lines+markers',
line=dict(color='orange'))

layout = go.Layout(title='test', yaxis=dict(title='test', range=[-320000,
21000]), yaxis2=dict(title='test', overlaying='y',
side='right', tickmode="sync", range=[-15, 5]),
legend=dict(x=1.06))

fig = go.Figure(data=[bar_trace, line_trace1], layout=layout)

fig.show()

Now I get this which is incorrect:

 
Joined
Mar 31, 2023
Messages
95
Reaction score
8
To align the bar and line in your plot when you have a range specified for yaxis and yaxis2, you can adjust the range values to ensure they are consistent. Here's an updated code snippet that aligns the bar and line:

pythonCopy code
import plotly.graph_objects as go

line_s = {
'Year/Quarter': ['Q1', 'Q2', 'Q3', 'Q4'],
'test1': [20000, 25000, 18000, 30000],
'test2': [-10, -5, -7, -12]
}

bar_trace = go.Bar(x=line_s['Year/Quarter'], y=line_s['test1'], name='test1')

line_trace1 = go.Scatter(
x=line_s['Year/Quarter'],
y=line_s['test2'],
name='test2',
yaxis='y2',
mode='lines+markers',
line=dict(color='orange')
)

layout = go.Layout(
title='test',
yaxis=dict(title='test', range=[0, 35000]),
yaxis2=dict(title='test', overlaying='y', side='right', tickmode="sync", range=[-15, 5]),
legend=dict(x=1.06)
)

fig = go.Figure(data=[bar_trace, line_trace1], layout=layout)

fig.show()

In the updated code, I've modified the range values for yaxis and yaxis2 to ensure that the bar and line align properly. Adjust the range values as needed to fit your data.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top