Search code examples
pythonanimationplotlyslider

Animated plotly express line showing only first day


I want to see instrument price with some discrete indicator. A slider that moves daily can show years of data more conveniently.

!pip install yfinance
import yfinance as yf
import plotly.express as px

df = yf.download("AAPL", period="5d",interval="1M")[['Close']]
df['day']=df.index.strftime('%d/%m/%Y')
df.loc[df.index.minute==0, "indicator"] = df['Close'] # dummy discrete indicator  

fig = px.line(df, y=["Close","indicator"],  animation_frame="day")
fig.update_traces(connectgaps=True)# to connect non nan values
fig.show()

This code works fine without animation. Animation shows only first day. I could not benefit from this answer.


Solution

  • You want to visualize the same time-slot for each day (not the whole 5d period) so you need to set x accordingly :

    df['time'] = df.index.strftime("%H:%M")
    fig = px.line(df, x="time", y=["Close","indicator"], animation_frame="day")
    

    NB. Plotly won't automatically compute the yaxis range during animation, so it must be specified manually to avoid scale jumps across frames. Also, the %H:%M time format makes the xaxis categorical (ie. not a 'date' axis type) so you will have to tweak the xaxis dtick according to the df['time'] unit (minutes, instead of milliseconds for date axes), eg.

    ymin, ymax = df['Close'].min(), df['Close'].max()
    room = (ymax - ymin) / 10
    
    fig.update_layout(
        yaxis_range=[ymin - room, ymax + room],
        xaxis_dtick=60
    )
    
    fig.show()
    

    See also : Animations in Python