Show Sidebar Hide Sidebar

Filled-Area Animation in Python

How to make an animated filled-area plot with apple stock data in Python.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version Check

Note: Animations are available in version 1.12.10+ Run pip install plotly --upgrade to update your Plotly version.

In [1]:
import plotly
plotly.__version__
Out[1]:
'1.12.12'

Import Data

Let us import some apple stock data for this animation.

In [2]:
import plotly.plotly as py
from plotly.grid_objs import Grid, Column
from plotly.tools import FigureFactory as FF 

import time
from datetime import datetime
import numpy as np
import pandas as pd
import pandas_datareader.data as web

appl = web.get_data_yahoo('AAPL', '2016-01-01', '2016-11-30')
apple_data_matrix = appl.head(10)

table = FF.create_table(apple_data_matrix)
py.iplot(table, filename='apple_data_table')
Out[2]:

Make the Grid

In [3]:
def to_unix_time(dt):
    epoch =  datetime.utcfromtimestamp(0)
    return (dt - epoch).total_seconds() * 1000

appl_price = list(appl['Adj Close'])
my_columns = []
for k in range(len(appl.index) - 1):
    my_columns.append(Column(appl.index[:k + 1], 'x{}'.format(k + 1)))   
    my_columns.append(Column(appl_price[:k + 1], 'y{}'.format(k + 1)))
grid = Grid(my_columns)
py.grid_ops.upload(grid, 'AAPL-daily-stock-price' + str(time.time()), auto_open=False)
Out[3]:
u'https://plot.ly/~AdamKulidjian/2201/'

Make the Figure

In [4]:
data=[dict(type='scatter',
           xsrc=grid.get_column_reference('x1'),
           ysrc= grid.get_column_reference('y1'),
           name='AAPL',
           mode='lines',
           line=dict(color= 'rgb(114, 186, 59)'),
           fill='tozeroy',
           fillcolor='rgba(114, 186, 59, 0.5)')]

axis=dict(ticklen=4,
          mirror=True,
          zeroline=False,
          showline=True,
          autorange=False,
          showgrid=False)

layout = dict(title='AAPL Daily Stock Price',
              font=dict(family='Balto'),
              showlegend=False,
              autosize=False,
              width=800,
              height=400,
              xaxis=dict(axis, **{'nticks':12, 'tickangle':-45,
                                  'range': [to_unix_time(datetime(2016, 1, 4)),
                                            to_unix_time(datetime(2016, 11, 30))]}),
              yaxis=dict(axis, **{'title': '$', 'range':[0,120]}),
              updatemenus=[dict(type='buttons',
                                showactive=False,
                                y=1,
                                x=1.1,
                                xanchor='right',
                                yanchor='top',
                                pad=dict(t=0, r=10),
                                buttons=[dict(label='Play',
                                              method='animate',
                                              args=[None, dict(frame=dict(duration=50, redraw=False), 
                                                               transition=dict(duration=0),
                                                               fromcurrent=True,
                                                               mode='immediate')])])])

frames=[{'data':[{'xsrc': grid.get_column_reference('x{}'.format(k + 1)),
                  'ysrc': grid.get_column_reference('y{}'.format(k + 1))}],
         'traces': [0]
        } for k in range(len(appl.index) - 1)]

fig=dict(data=data, layout=layout, frames=frames)
py.icreate_animations(fig, 'AAPL-stockprice' + str(time.time()))
Out[4]:

Reference

For additional information on filled area plots in Plotly see: https://plot.ly/python/filled-area-plots/. For more documentation on creating animations with Plotly, see https://plot.ly/python/#animations.

Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.