HappyLifelongLearner
HappyLifelongLearner

Reputation: 149

How to create an animated line plot with ploty express?

I'm trying to create an animated line plot to illustrate the price increase of 3 different asset classes over time (year), but it doesn't work and I don't know why!

What I've done so far:

  1. get closing price data for each asset
start = datetime.datetime(2010,7,01) 
end = datetime.datetime(2021,7,01) 
data = pdr.get_data_yahoo(['BTC-USD', 'GC=F','^GSPC'],startDate,endDate)['Adj Close']
  1. transpose columns into rows to avoid a lot of calculations
data['Date'] = data.index
data['Year'] = data.index.year
dataNew =data.melt(['Date', 'Year'], var_name='Asset')
dataNew = dataNew.rename(columns = {'value': 'Price'})

  1. plot
fig = px.line(dataNew,
             x = 'Date',
             y = 'Price',
             range_y=[0,50000],
             color = 'Asset',
             animation_frame = 'Year')
    st.write(fig)

Output:

Output

Upvotes: 3

Views: 1968

Answers (1)

vestland
vestland

Reputation: 61214

Short answer:

This is in fact very much possible, and the only additions you'll have to make to a standard px.line() time series using axes of type date plot setup is this:

# input data
dfi = px.data.stocks().head(50)

# new datastructure for animation
df = pd.DataFrame() # container for df with new datastructure
for i in np.arange(start,obs):
    dfa = dfi.head(i).copy()
    dfa['ix']=i
    df = pd.concat([df, dfa])

The cool details:

Contrary to what seems to be the most common belief, and contrary to my own comments just a few minutes ago, this is in fact possible to do with px.line and a set of time series as you're describing. As long as you massage the dataset just a little bit. The only real drawback seems to be that it might not work very well for larger datasets, since the amount of data that the figure structure will contain will be huge. But let's get back to the boring details after the cool stuff. The snippet below and the dataset px.data.stocks() will produce the following figure:

Plot 1 - Animation using the play button:

enter image description here

When the animation has come to an end, you can also subset the lines however you'd like.

Plot 2 - Animation using the slider:

enter image description here

The boring details:

I'll get back to this if the OP or anyone else is interested

Complete code:

import pandas as pd
import numpy as np
import plotly.express as px

# input data
dfi = px.data.stocks().head(50)
dfi['date'] = pd.to_datetime(dfi['date'])
start = 12
obs = len(dfi)

# new datastructure for animation
df = pd.DataFrame() # container for df with new datastructure
for i in np.arange(start,obs):
    dfa = dfi.head(i).copy()
    dfa['ix']=i
    df = pd.concat([df, dfa])

# plotly figure
fig = px.line(df, x = 'date', y = ['GOOG', 'AAPL', 'AMZN', 'FB', 'NFLX', 'MSFT'],
              animation_frame='ix',
              # template = 'plotly_dark',
              width=1000, height=600)

# attribute adjusments
fig.layout.updatemenus[0].buttons[0]['args'][1]['frame']['redraw'] = True
fig.show()

Upvotes: 3

Related Questions