Search code examples
plotlyrangeslider

How can i designate specific trace when using range slider in plotly?


I've known It's common way making figure object with make_subplot first, fill it with add_trace second, and make range slider with 'update_layout' finally.

for example.

fig = make_subplot(rows=2, cols=1...)
fig.add_trace(go.CandleStick(...))  -----------------------------------------(first trace)
fig.add_trace(go.CandleStick(...))  -----------------------------------------(second trace)

fig.update_layout(xaxis==dict(rangeslider=dict(visible=True)))

this rangeslider is usually applied to entire figure(all of first trace and second trace) but, i want to know how to apply rangeslider to each trace separately

i could haven't this way in plotly document..


Solution

  • Below shows multiple candlesticks in different subplots. I recommend having ticker with rangeslider last so positioning works ok

    import pandas as pd
    import yfinance as yf
    import datetime as dt
    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    
    # Initial data & get dataframe
    start = dt.date(2022, 3, 1)
    end = dt.date(2022, 3, 7)
    
    fig = make_subplots(
        rows=2,
        cols=1,
    )
    
    for i, ticker in enumerate(["MSFT", "AAPL"]):
        df = yf.download(ticker, start, end, progress=False, interval="1h")
    
        fig.add_trace(
            go.Candlestick(
                x=df.index,
                open=df["Open"],
                high=df["High"],
                low=df["Low"],
                close=df["Close"],
                name=ticker
            ),
            row=i + 1,
            col=1,
        )
    
    fig.update_xaxes(
        rangebreaks=[
            dict(bounds=[16, 9.5], pattern="hour"),  # hide hours from 4pm to 9:30am
        ]
    )
    fig.update_layout(xaxis={"rangeslider":{"visible":False}})
    

    enter image description here