Dynamically Changing X-axis and Y-axis Titles Using layout.updatemenus[] Dropdown

Viewed 1500

I have Python Dash App which displays a Plotly graph_object.scatter plot with multiple traces that I can switch between using a layout.updatemenus[] dropdown menu.

The problem that I'm facing is that depending on which dropdown menu option is selected, the x-axis and y-axis should have different titles.

As of now, neither axis has any title, but I can add a permanent title (that is, one that does not change dynamically based on which trace is showing) by using the xaxis_title and yaxis_title attributes of the figure.update_layout method. I cannot, however, pass a list or a dictionary for xaxis_title or yaxis_title (it only accepts a string or an int).

I'm currently envisioning a series of if/else statements that finds which dropdown menu option currently has 'ShowActive' set to True and changes the xaxis_title and yaxis_title attributes based on that. But I don't know how to write it so that this axis-title-changing function will run whenever a new menu option is selected.

I can update this question with code samples if necessary.

1 Answers

You can change the x-axis labels and y-axis labels on update as follows:

updatemenus = list([
dict(active=-1,
     buttons=list([   
        dict(label = 'High',
             method = 'update',
             args = [{'visible': [True, True, False, False]},
                     {'title': 'Yahoo High',
                      'xaxis': {'title': 'Date'},
                      'yaxis': {'title': 'High Price - Dollars'},
                      'annotations': high_annotations}]),
        dict(label = 'Low',
             method = 'update',
             args = [{'visible': [False, False, True, True]},
                     {'title': 'Yahoo Low',
                      'xaxis': {'title': 'Date'},
                      'yaxis': {'title': 'Low Price - Dollars'},
                      'annotations': low_annotations}]),

In args, you can change the 'xaxis' : {'title' : 'CHANGE X-AXIS LABEL'} to achieve this.

Answer sourced from: https://community.plotly.com/t/changing-the-xy-axis-titles-with-dropdown-menu/5421/2.

Related