{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### New to Plotly?\n",
"Plotly's Python library is free and open source! [Get started](https://plotly.com/python/getting-started/) by downloading the client and [reading the primer](https://plotly.com/python/getting-started/).\n",
"
You can set up Plotly to work in [online](https://plotly.com/python/getting-started/#initialization-for-online-plotting) or [offline](https://plotly.com/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plotly.com/python/getting-started/#start-plotting-online).\n",
"
We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Version Check\n",
"Note: Animations are available in version 1.12.10+\n",
"Run `pip install plotly --upgrade` to update your Plotly version."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'1.12.12'"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import plotly\n",
"plotly.__version__"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Make the Grid\n",
"Our goal is to generate the contours plots of the bivariate normal distributions of mean vector (0,0), standard deviation vector (1,1), and correlation, $\\rho$ , varying from `(−1, 1)`. Since we are making an online animation, we must create our grid first and upload it."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"u'https://plotly.com/~AdamKulidjian/2189/'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import plotly.plotly as py\n",
"from plotly.grid_objs import Grid, Column\n",
"\n",
"import time\n",
"import numpy as np\n",
"from scipy.stats import multivariate_normal as Nd\n",
"\n",
"colorscale = [\n",
" [0.0, 'rgb(25, 23, 10)'], \n",
" [0.05, 'rgb(69, 48, 44)'],\n",
" [0.1, 'rgb(114, 52, 47)'],\n",
" [0.15, 'rgb(155, 58, 49)'],\n",
" [0.2, 'rgb(194, 70, 51)'],\n",
" [0.25, 'rgb(227, 91, 53)'],\n",
" [0.3, 'rgb(250, 120, 56)'],\n",
" [0.35, 'rgb(255, 152, 60)'],\n",
" [0.4, 'rgb(255, 188, 65)'],\n",
" [0.45, 'rgb(236, 220, 72)'],\n",
" [0.5, 'rgb(202, 243, 80)'],\n",
" [0.55, 'rgb(164, 252, 93)'],\n",
" [0.6, 'rgb(123, 245, 119)'],\n",
" [0.65, 'rgb(93, 225, 162)'],\n",
" [0.7, 'rgb(84, 196, 212)'],\n",
" [0.75, 'rgb(99, 168, 238)'],\n",
" [0.8, 'rgb(139, 146, 233)'],\n",
" [0.85, 'rgb(190, 139, 216)'],\n",
" [0.9, 'rgb(231, 152, 213)'],\n",
" [0.95, 'rgb(241, 180, 226)'],\n",
" [1.0, 'rgb(206, 221, 250)']\n",
"]\n",
"\n",
"# returns V=(X,Y)~N(m, Sigma)\n",
"def bivariate_N(m=[0., 0.], stdev=[1.0, 1.0], rho=0):\n",
" cov = rho*stdev[0] * stdev[1] # covariance(X,Y)\n",
" Sigma = np.array([[stdev[0]**2, cov], [cov, stdev[1]**2]]) # covariance matrix \n",
" return Nd(mean=m, cov=Sigma) # joint distribution of (X,Y), of mean vector, m, and cov matrix, Sigma\n",
"\n",
"# returns the pdf of the bivariate normal distribution\n",
"def pdf_bivariate_N(m, stdev, V):\n",
" X = np.linspace(m[0] - 3*stdev[0], m[0] + 3*stdev[0], 100)\n",
" Y = np.linspace(m[1] - 3*stdev[1], m[1] + 3*stdev[1], 100)\n",
" x, y = np.meshgrid(X, Y)\n",
" pos = np.empty(x.shape + (2, ))\n",
" pos[:, :, 0] = x; pos[:, :, 1] = y\n",
" z = V.pdf(pos)\n",
" return X, Y, z\n",
"\n",
"correls=[-0.95, -0.85, -0.75, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 0.75, 0.85, 0.95]\n",
"\n",
"m=[0., 0.]\n",
"stdev=[1., 1.]\n",
"V=bivariate_N()\n",
"x, y=pdf_bivariate_N(m, stdev, V)[:2]\n",
"my_columns=[Column(x, 'x'), Column(y, 'y')]\n",
"zvmax=[]\n",
"for k, rho in enumerate(correls):\n",
" V = bivariate_N(rho = rho)\n",
" z = pdf_bivariate_N(m, stdev, V)[2]\n",
" zvmax.append(np.max(z))\n",
" my_columns.append(Column(z, 'z{}'.format(k + 1)))\n",
"grid = Grid(my_columns)\n",
"py.grid_ops.upload(grid, 'norm-bivariate1'+str(time.time()), auto_open=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Make the Figure\n",
"Make the `Figure` which references columns from the grid we made. The `Figure` takes `Data`, `Layout` and `Frames`."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"data=[dict(type='heatmap',\n",
" xsrc=grid.get_column_reference('x'),\n",
" ysrc=grid.get_column_reference('y'), \n",
" zsrc=grid.get_column_reference('z1'), \n",
" zmin=0,\n",
" zmax=zvmax[6],\n",
" zsmooth='best', \n",
" colorscale=colorscale, \n",
" colorbar=dict(thickness=20, ticklen=4))]\n",
"\n",
"title='Contour plot for bivariate normal distribution'+\\\n",
"'
N(m=[0,0], sigma=[1,1], rho in (-1, 1))'\n",
"\n",
"layout = dict(title=title,\n",
" autosize=False,\n",
" height=600,\n",
" width=600,\n",
" hovermode='closest',\n",
" xaxis=dict(range=[-3, 3], autorange=False),\n",
" yaxis=dict(range=[-3, 3], autorange=False),\n",
" showlegend=False,\n",
" updatemenus=[dict(type='buttons', showactive=False,\n",
" y=1, x=-0.05, xanchor='right',\n",
" yanchor='top', pad=dict(t=0, r=10),\n",
" buttons=[dict(label='Play',\n",
" method='animate',\n",
" args=[None,\n",
" dict(frame=dict(duration=100, \n",
" redraw=True),\n",
" transition=dict(duration=0),\n",
" fromcurrent=True,\n",
" mode='immediate')])])])\n",
"\n",
"frames=[dict(data=[dict(zsrc=grid.get_column_reference('z{}'.format(k + 1)),\n",
" zmax=zvmax[k])],\n",
" traces=[0],\n",
" name='frame{}'.format(k),\n",
" ) for k in range(len(correls))]\n",
" \n",
" \n",
"fig=dict(data=data, layout=layout, frames=frames) \n",
"py.icreate_animations(fig, filename='animheatmap'+str(time.time()))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Reference\n",
"For additional information and attributes for creating heatmaps in Plotly see: https://plotly.com/python/reference/#heatmap.\n",
"For more documentation on creating animations with Plotly, see https://plotly.com/python/#animations."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Collecting git+https://github.com/plotly/publisher.git\n",
" Cloning https://github.com/plotly/publisher.git to /private/var/folders/tc/bs9g6vrd36q74m5t8h9cgphh0000gn/T/pip-tX0gQL-build\n",
"Installing collected packages: publisher\n",
" Found existing installation: publisher 0.10\n",
" Uninstalling publisher-0.10:\n",
" Successfully uninstalled publisher-0.10\n",
" Running setup.py install for publisher ... \u001b[?25l-\b \b\\\b \bdone\n",
"\u001b[?25hSuccessfully installed publisher-0.10\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/nbconvert.py:13: ShimWarning: The `IPython.nbconvert` package has been deprecated. You should import from nbconvert instead.\n",
" \"You should import from nbconvert instead.\", ShimWarning)\n",
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/publisher/publisher.py:53: UserWarning: Did you \"Save\" this notebook before running this command? Remember to save, always save.\n",
" warnings.warn('Did you \"Save\" this notebook before running this command? '\n"
]
}
],
"source": [
"from IPython.display import display, HTML\n",
"\n",
"display(HTML(''))\n",
"display(HTML(''))\n",
"\n",
"!pip install git+https://github.com/plotly/publisher.git --upgrade\n",
"import publisher\n",
"publisher.publish(\n",
" 'heatmap.ipynb', 'python/heatmap-animation/', 'Heatmap Animation | plotly',\n",
" 'How to make an animated heatmap in Python.',\n",
" title='Heatmap Animation | plotly',\n",
" name='Heatmap Animation',\n",
" language='python',\n",
" page_type='example_index', has_thumbnail='true', thumbnail='thumbnail/heatmap_animation.gif',\n",
" ipynb= '~notebook_demo/131',\n",
" display_as='animations', order=4)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.12"
}
},
"nbformat": 4,
"nbformat_minor": 0
}