Search code examples
pythonplotlyaxis

Plotly: difference between fig.update_layout({'yaxis': dict(matches=None)}) and fig.update_yaxes(matches=None)


I am trying to work out the difference between:

  • fig.update_layout({'yaxis': dict(matches=None)})
  • fig.update_yaxes(matches=None)

I thought they were the same, but fig.update_layout({'yaxis': dict(matches=None)}) doesn't change the yaxis as expected.

Here is the example code:

import plotly.express as px
import plotly
print("plotly version: " , plotly.__version__)
# Sample data
data = {
    'Variable': ['A', 'A', 'B', 'B', 'C', 'C'],
    'Value': [1, 2, 3, 4, 5, 6]
}

# Create box plot
fig = px.box(data, y='Value', facet_row='Variable')
fig.update_layout(height=400, width =400)
fig.update_layout({'yaxis': dict(matches=None)})
fig.show()

fig.update_yaxes(matches=None)
fig.show()

OUT:

enter image description here


Solution

  • This is happening because when you use the facet_row argument, you will generate multiple yaxes. You can set them individually like this:

    fig.update_layout({'yaxis': dict(matches=None)})
    fig.update_layout({'yaxis2': dict(matches=None)})
    fig.update_layout({'yaxis3': dict(matches=None)})
    

    Or in a more dynamic way:

    ## retrieve all yaxis names: ['yaxis', 'yaxis2', 'yaxis3']
    yaxis_names = ['yaxis'] + [axis_name for axis_name in fig.layout._subplotid_props if 'yaxis' in axis_name]
    yaxis_layout_dict = {yaxis_name:dict(matches=None) for yaxis_name in yaxis_names}
    fig.update_layout(yaxis_layout_dict)