pythonplotplotlyaxesplotly-dash

How to enable and disable the logarithmic scale as a viewer in Plotly?


I am recently exploring Plotly and I wonder if there is a way for sharing a plot and let the viewer switch between a logarithmic axis and linear axis.

Any suggestion?


Solution

  • Plotly has a dropdown feature which allows the user to dynamically update the plot styling and/or the traces being displayed. Below is a minimal working example of a plot where the user can switch between a logarithmic and linear scale.

    import plotly
    import plotly.graph_objs as go
    
    
    x = [1, 2, 3]
    y = [1000, 10000, 100000]
    y2 = [5000, 10000, 90000]
    
    trace1 = go.Bar(x=x, y=y, name='trace1')
    trace2 = go.Bar(x=x, y=y2, name='trace2', visible=False)
    
    
    data = [trace1, trace2]
    
    updatemenus = list([
        dict(active=1,
             buttons=list([
                dict(label='Log Scale',
                     method='update',
                     args=[{'visible': [True, True]},
                           {'title': 'Log scale',
                            'yaxis': {'type': 'log'}}]),
                dict(label='Linear Scale',
                     method='update',
                     args=[{'visible': [True, False]},
                           {'title': 'Linear scale',
                            'yaxis': {'type': 'linear'}}])
                ]),
            )
        ])
    
    layout = dict(updatemenus=updatemenus, title='Linear scale')
    fig = go.Figure(data=data, layout=layout)
    
    plotly.offline.iplot(fig)
    

    I added two traces to the data list to show how traces can also be added or removed from a plot. This can be controlled by the visible list in updatemenus for each button.