pythonplotlyvisualizationyaxisplotly.graph-objects

How to adjust steps of y-axis


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


Solution

  • 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