1

I have a plot in which I have two y-axis. The y-axis on the left represent the bar chart and the y-axis on the left represent the two lines. The problem is that the left y-axis currently creates individual steps for the y-axis values, which results in additional y-axis lines on the left side. I want the left y-axis to align with the tick marks on the right y-axis, so that the y-axis lines match, this should go automatically (so that it is easy to use the plot for other dataframes aswell). How to do this?

import plotly.graph_objects as go

bar_trace = go.Bar(x=line_df['Year/Quarter'], y=line_df['CUR (€)'], name='CUR (€)')

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

line_trace2 = go.Scatter(x=line_df['Year/Quarter'], y=line_df['CUR PP'], name='CUR PP', 
                 yaxis='y2', mode='lines+markers', line=dict(color='red'))

layout = go.Layout(title='test', 
           yaxis=dict(title='test'), 
           yaxis2=dict(title='test', overlaying='y', side='right'))

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

fig.show()

enter image description here

hvahva
  • 51
  • 5

1 Answers1

1

If you're on Plotly 5.13 or later then try setting tickmode="sync" for the yaxis2 definition.

This should preserve the y-axis ranges but ensure the ticks themselves align.

The Plotly documentation has an example you can check out.

https://plotly.com/python/multiple-axes/#sync-axes-ticks

miqh
  • 3,624
  • 2
  • 28
  • 38
  • I have tried updating to plotly 5.13 using "!pip install plotly==5.14.0", running this I get "Requirement already satisfied", but I still get a error while using tickmode="sync" for the yaxis2 "ValueError: Invalid value of type 'builtins.str' received for the 'tickmode' property of layout.yaxis Received value: 'sync'" How do I use plotly 5.13 or later versions? – hvahva Apr 05 '23 at 05:44
  • I just had to restart the kernal :) . It works now, thanks alot – hvahva Apr 05 '23 at 05:58