Y-axis autoscaling with x-range sliders

Hi @TOTORO and @s1kor,

I came up with a Python solution to this using the new FigureWidget class. The basic idea is the register a Python callback function to run whenever the xaxis range changes. In response, the callback function computes and applies a new yaxis range.

First construct a simple scatter plot line plot with a range slider. Make sure to set the

import plotly.graph_objs as go 

from datetime import datetime
import pandas_datareader.data as web

df = web.DataReader('AAPL.US', 'quandl',
                    datetime(2007, 10, 1),
                    datetime(2009, 4, 1))

# Make sure dates are in ascending order
# We need this for slicing in the callback below
df.sort_index(ascending=True, inplace=True)

trace = go.Scatter(x=list(df.index),
                   y=list(df.High))

data = [trace]
layout = dict(
    title='Time series with range slider and selectors',
    xaxis=dict(
        rangeselector=dict(
            buttons=list([
                dict(count=1,
                     label='1m',
                     step='month',
                     stepmode='backward'),
                dict(count=6,
                     label='6m',
                     step='month',
                     stepmode='backward'),
                dict(count=1,
                    label='YTD',
                    step='year',
                    stepmode='todate'),
                dict(count=1,
                    label='1y',
                    step='year',
                    stepmode='backward'),
                dict(step='all')
            ])
        ),
        rangeslider=dict(
            visible = True
        ),
        type='date'
    )
)

fig = go.FigureWidget(data=data, layout=layout)
fig

Then install a property change callback to update the yaxis range

def zoom(layout, xrange):
    in_view = df.loc[fig.layout.xaxis.range[0]:fig.layout.xaxis.range[1]]
    fig.layout.yaxis.range = [in_view.High.min() - 10, in_view.High.max() + 10]

fig.layout.on_change(zoom, 'xaxis.range')

Now, when you manipulate the range slider, the yaxis will automatically adjust to the data in view (plus a 10 unit buffer on each side, you should adjust that to what looks right for your data.

Hope that helps!
-Jon

6 Likes