{ "metadata": { "name": "", "signature": "sha256:3b0b4921e53d34db821220fdecc0140f0b8d8e6bb636add1ef8519e64cf8952d" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Subplots and small multiples\n", "## with plotly and `plotly.tools.make_subplots`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from plotly import tools # functions to help build plotly graphs\n", "import plotly.plotly as py # module that communicates with plotly \n", "from plotly.graph_objs import * # graph objects, subclasses of lists and dicts, that are used to describe plotly graphs" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Simple subplots" ] }, { "cell_type": "code", "collapsed": false, "input": [ "fig = tools.make_subplots(rows=2)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This is the format of your plot grid:\n", "[ (1,1) x1,y1 ]\n", "[ (2,1) x2,y2 ]\n", "\n" ] } ], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "fig.append_trace(Scatter(x=[1,2,3], y=[2,1,2], name='top trace'), 1, 1)\n", "fig.append_trace(Scatter(x=[1,2,3], y=[2,3,2], name='bottom trace'), 2, 1)\n", "py.iplot(fig, filename='subplot example')" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "" ], "metadata": {}, "output_type": "pyout", "prompt_number": 3, "text": [ "" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Shared axes" ] }, { "cell_type": "code", "collapsed": false, "input": [ "fig = tools.make_subplots(rows=2, shared_xaxes=True, print_grid=True)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This is the format of your plot grid:\n", "[ (1,1) x1,y1 ]\n", "[ (2,1) x1,y2 ]\n", "\n" ] } ], "prompt_number": 4 }, { "cell_type": "code", "collapsed": false, "input": [ "fig.append_trace(Scatter(x=[1,2,3], y=[2,1,2]), 1, 1)\n", "fig.append_trace(Scatter(x=[2,3,4], y=[2,3,2]), 2, 1)\n", "py.iplot(fig, filename='shared xaxis')" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "" ], "metadata": {}, "output_type": "pyout", "prompt_number": 5, "text": [ "" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### loops" ] }, { "cell_type": "code", "collapsed": false, "input": [ "nr = 6\n", "nc = 6\n", "fig = tools.make_subplots(rows=nr, cols=nc, print_grid=False)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 6 }, { "cell_type": "code", "collapsed": false, "input": [ "for i in range(1, nr+1):\n", " for j in range(1, nc+1):\n", " fig.append_trace(Scatter(x=[1], y=[1], \n", " text=['({}, {})'.format(i,j)], \n", " mode='markers+text',\n", " textposition='top'), row=i, col=j)\n", "\n", "fig['layout']['showlegend'] = False\n", "py.iplot(fig, filename='6x6')" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "" ], "metadata": {}, "output_type": "pyout", "prompt_number": 7, "text": [ "" ] } ], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ... with shared axes" ] }, { "cell_type": "code", "collapsed": false, "input": [ "nr = 6\n", "nc = 6\n", "fig = tools.make_subplots(rows=nr, cols=nc, print_grid=False,\n", " shared_xaxes=True, shared_yaxes=True)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 8 }, { "cell_type": "code", "collapsed": false, "input": [ "for i in range(1, nr+1):\n", " for j in range(1, nc+1):\n", " fig.append_trace(Scatter(x=[1], y=[1], \n", " text=['({}, {})'.format(i,j)], \n", " mode='markers+text',\n", " textposition='top'), row=i, col=j)\n", "\n", "fig['layout']['showlegend'] = False\n", "py.iplot(fig, filename='6x6 shared')" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "" ], "metadata": {}, "output_type": "pyout", "prompt_number": 9, "text": [ "" ] } ], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### insets" ] }, { "cell_type": "code", "collapsed": false, "input": [ "fig = tools.make_subplots(insets=[{'cell': (1,1), 'l': 0.7, 'b': 0.7}],\n", " print_grid=True)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This is the format of your plot grid:\n", "[ (1,1) x1,y1 ]\n", "\n", "With insets:\n", "[ x2,y2 ] over [ (1,1) x1,y1 ]\n", "\n" ] } ], "prompt_number": 10 }, { "cell_type": "code", "collapsed": false, "input": [ "fig.append_trace(Scatter(x=[1,2,3], y=[2,1,2]), 1, 1)\n", "fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]\n", "py.iplot(fig, filename='inset example')" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "" ], "metadata": {}, "output_type": "pyout", "prompt_number": 11, "text": [ "" ] } ], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### spanning columns" ] }, { "cell_type": "code", "collapsed": false, "input": [ "fig = tools.make_subplots(rows=2, cols=2,\n", " specs=[[{}, {}],\n", " [{'colspan': 2}, None]],\n", " print_grid=True)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This is the format of your plot grid:\n", "[ (1,1) x1,y1 ] [ (1,2) x2,y2 ]\n", "[ (2,1) x3,y3 - ]\n", "\n" ] } ], "prompt_number": 12 }, { "cell_type": "code", "collapsed": false, "input": [ "fig.append_trace(Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=1)\n", "fig.append_trace(Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=2)\n", "fig.append_trace(Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1)\n", "\n", "py.iplot(fig, filename='irregular spacing')" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "" ], "metadata": {}, "output_type": "pyout", "prompt_number": 13, "text": [ "" ] } ], "prompt_number": 13 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### unique arrangements" ] }, { "cell_type": "code", "collapsed": false, "input": [ "fig = tools.make_subplots(rows=5, cols=2,\n", " specs=[[{}, {'rowspan': 2}],\n", " [{}, None],\n", " [{'rowspan': 2, 'colspan': 2}, None],\n", " [None, None],\n", " [{}, {}]],\n", " print_grid=True)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This is the format of your plot grid:\n", "[ (1,1) x1,y1 ] [ (1,2) x2,y2 ]\n", "[ (2,1) x3,y3 ] | \n", "[ (3,1) x4,y4 - ]\n", " | | \n", "[ (5,1) x5,y5 ] [ (5,2) x6,y6 ]\n", "\n" ] } ], "prompt_number": 14 }, { "cell_type": "code", "collapsed": false, "input": [ "fig.append_trace(Scatter(x=[1,2],y=[1,4],name='(1,1)'), 1, 1)\n", "fig.append_trace(Scatter(x=[1,2],y=[1,4],name='(2,1)'), 2, 1)\n", "fig.append_trace(Scatter(x=[1,2],y=[1,4],name='(3,1)'), 3, 1)\n", "fig.append_trace(Scatter(x=[1,2],y=[1,4],name='(5,1)'), 5, 1)\n", "\n", "fig.append_trace(Scatter(x=[1,2],y=[1,4],name='(1,2)'), 1, 2)\n", "fig.append_trace(Scatter(x=[1,2],y=[1,4],name='(5,2)'), 5, 2)\n", "\n", "py.iplot(fig, filename='subplot unique arrangement')" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "" ], "metadata": {}, "output_type": "pyout", "prompt_number": 15, "text": [ "" ] } ], "prompt_number": 15 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### walkthrough" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`tools.make_subplots` *generates* `Figure` objects for you.\n", "\n", "Need some help? Call `help`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "help(tools.make_subplots)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on function make_subplots in module plotly.tools:\n", "\n", "make_subplots(rows=1, cols=1, shared_xaxes=False, shared_yaxes=False, start_cell='top-left', print_grid=True, **kwargs)\n", " Return an instance of plotly.graph_objs.Figure\n", " with the subplots domain set in 'layout'.\n", " \n", " Example 1:\n", " # stack two subplots vertically\n", " fig = tools.make_subplots(rows=2)\n", " \n", " This is the format of your plot grid:\n", " [ (1,1) x1,y1 ]\n", " [ (2,1) x2,y2 ]\n", " \n", " fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]\n", " fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]\n", " \n", " # or see Figure.append_trace\n", " \n", " Example 2:\n", " # subplots with shared x axes\n", " fig = tools.make_subplots(rows=2, shared_xaxes=True)\n", " \n", " This is the format of your plot grid:\n", " [ (1,1) x1,y1 ]\n", " [ (2,1) x1,y2 ]\n", " \n", " \n", " fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]\n", " fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], yaxis='y2')]\n", " \n", " Example 3:\n", " # irregular subplot layout (more examples below under 'specs')\n", " fig = tools.make_subplots(rows=2, cols=2,\n", " specs=[[{}, {}],\n", " [{'colspan': 2}, None]])\n", " \n", " This is the format of your plot grid!\n", " [ (1,1) x1,y1 ] [ (1,2) x2,y2 ]\n", " [ (2,1) x3,y3 - ]\n", " \n", " fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]\n", " fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]\n", " fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x3', yaxis='y3')]\n", " \n", " Example 4:\n", " # insets\n", " fig = tools.make_subplots(insets=[{'cell': (1,1), 'l': 0.7, 'b': 0.3}])\n", " \n", " This is the format of your plot grid!\n", " [ (1,1) x1,y1 ]\n", " \n", " With insets:\n", " [ x2,y2 ] over [ (1,1) x1,y1 ]\n", " \n", " fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]\n", " fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]\n", " \n", " Keywords arguments with constant defaults:\n", " \n", " rows (kwarg, int greater than 0, default=1):\n", " Number of rows in the subplot grid.\n", " \n", " cols (kwarg, int greater than 0, default=1):\n", " Number of columns in the subplot grid.\n", " \n", " shared_xaxes (kwarg, boolean or list, default=False)\n", " Assign shared x axes.\n", " If True, subplots in the same grid column have one common\n", " shared x-axis at the bottom of the gird.\n", " \n", " To assign shared x axes per subplot grid cell (see 'specs'),\n", " send list (or list of lists, one list per shared x axis)\n", " of cell index tuples.\n", " \n", " shared_yaxes (kwarg, boolean or list, default=False)\n", " Assign shared y axes.\n", " If True, subplots in the same grid row have one common\n", " shared y-axis on the left-hand side of the gird.\n", " \n", " To assign shared y axes per subplot grid cell (see 'specs'),\n", " send list (or list of lists, one list per shared y axis)\n", " of cell index tuples.\n", " \n", " start_cell (kwarg, 'bottom-left' or 'top-left', default='top-left')\n", " Choose the starting cell in the subplot grid used to set the\n", " domains of the subplots.\n", " \n", " print_grid (kwarg, boolean, default=True):\n", " If True, prints a tab-delimited string representation of\n", " your plot grid.\n", " \n", " Keyword arguments with variable defaults:\n", " \n", " horizontal_spacing (kwarg, float in [0,1], default=0.2 / cols):\n", " Space between subplot columns.\n", " Applies to all columns (use 'specs' subplot-dependents spacing)\n", " \n", " vertical_spacing (kwarg, float in [0,1], default=0.3 / rows):\n", " Space between subplot rows.\n", " Applies to all rows (use 'specs' subplot-dependents spacing)\n", " \n", " specs (kwarg, list of lists of dictionaries):\n", " Subplot specifications.\n", " \n", " ex1: specs=[[{}, {}], [{'colspan': 2}, None]]\n", " \n", " ex2: specs=[[{'rowspan': 2}, {}], [None, {}]]\n", " \n", " - Indices of the outer list correspond to subplot grid rows\n", " starting from the bottom. The number of rows in 'specs'\n", " must be equal to 'rows'.\n", " \n", " - Indices of the inner lists correspond to subplot grid columns\n", " starting from the left. The number of columns in 'specs'\n", " must be equal to 'cols'.\n", " \n", " - Each item in the 'specs' list corresponds to one subplot\n", " in a subplot grid. (N.B. The subplot grid has exactly 'rows'\n", " times 'cols' cells.)\n", " \n", " - Use None for blank a subplot cell (or to move pass a col/row span).\n", " \n", " - Note that specs[0][0] has the specs of the 'start_cell' subplot.\n", " \n", " - Each item in 'specs' is a dictionary.\n", " The available keys are:\n", " \n", " * is_3d (boolean, default=False): flag for 3d scenes\n", " * colspan (int, default=1): number of subplot columns\n", " for this subplot to span.\n", " * rowspan (int, default=1): number of subplot rows\n", " for this subplot to span.\n", " * l (float, default=0.0): padding left of cell\n", " * r (float, default=0.0): padding right of cell\n", " * t (float, default=0.0): padding right of cell\n", " * b (float, default=0.0): padding bottom of cell\n", " \n", " - Use 'horizontal_spacing' and 'vertical_spacing' to adjust\n", " the spacing in between the subplots.\n", " \n", " insets (kwarg, list of dictionaries):\n", " Inset specifications.\n", " \n", " - Each item in 'insets' is a dictionary.\n", " The available keys are:\n", " \n", " * cell (tuple, default=(1,1)): (row, col) index of the\n", " subplot cell to overlay inset axes onto.\n", " * is_3d (boolean, default=False): flag for 3d scenes\n", " * l (float, default=0.0): padding left of inset\n", " in fraction of cell width\n", " * w (float or 'to_end', default='to_end') inset width\n", " in fraction of cell width ('to_end': to cell right edge)\n", " * b (float, default=0.0): padding bottom of inset\n", " in fraction of cell height\n", " * h (float or 'to_end', default='to_end') inset height\n", " in fraction of cell height ('to_end': to cell top edge)\n", "\n" ] } ], "prompt_number": 16 }, { "cell_type": "code", "collapsed": false, "input": [ "fig = tools.make_subplots(rows=2)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This is the format of your plot grid:\n", "[ (1,1) x1,y1 ]\n", "[ (2,1) x2,y2 ]\n", "\n" ] } ], "prompt_number": 17 }, { "cell_type": "markdown", "metadata": {}, "source": [ "`fig` is a subclass of a `dict`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print fig" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "{'data': [], 'layout': {'yaxis1': {'domain': [0.575, 1.0], 'anchor': 'x1'}, 'yaxis2': {'domain': [0.0, 0.425], 'anchor': 'x2'}, 'xaxis2': {'domain': [0.0, 1.0], 'anchor': 'y2'}, 'xaxis1': {'domain': [0.0, 1.0], 'anchor': 'y1'}}}\n" ] } ], "prompt_number": 18 }, { "cell_type": "markdown", "metadata": {}, "source": [ "`to.string()` pretty prints the object" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print fig.to_string()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Figure(\n", " data=Data(),\n", " layout=Layout(\n", " xaxis1=XAxis(\n", " domain=[0.0, 1.0],\n", " anchor='y1'\n", " ),\n", " xaxis2=XAxis(\n", " domain=[0.0, 1.0],\n", " anchor='y2'\n", " ),\n", " yaxis1=YAxis(\n", " domain=[0.575, 1.0],\n", " anchor='x1'\n", " ),\n", " yaxis2=YAxis(\n", " domain=[0.0, 0.425],\n", " anchor='x2'\n", " )\n", " )\n", ")\n" ] } ], "prompt_number": 19 }, { "cell_type": "markdown", "metadata": {}, "source": [ "`fig` subclasses a `dict`, so access members just like you would in a `dict`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "fig['layout']" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 20, "text": [ "{'xaxis1': {'anchor': 'y1', 'domain': [0.0, 1.0]},\n", " 'xaxis2': {'anchor': 'y2', 'domain': [0.0, 1.0]},\n", " 'yaxis1': {'anchor': 'x1', 'domain': [0.575, 1.0]},\n", " 'yaxis2': {'anchor': 'x2', 'domain': [0.0, 0.425]}}" ] } ], "prompt_number": 20 }, { "cell_type": "markdown", "metadata": {}, "source": [ "it's a bit different than a straight dictionary because only certain keys are allowed.\n", "\n", "each key and value describes something about a plotly graph, so it's pretty strict.\n", "\n", "for example, you can't initialize a `Figure` with an invalid key. we'll throw an exception." ] }, { "cell_type": "code", "collapsed": false, "input": [ "import traceback\n", "try:\n", " Figure(nonsense=3)\n", "except:\n", " print traceback.format_exc()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Traceback (most recent call last):\n", " File \"\", line 3, in \n", " Figure(nonsense=3)\n", " File \"/usr/local/lib/python2.7/dist-packages/plotly/graph_objs/graph_objs.py\", line 920, in __init__\n", " super(Figure, self).__init__(*args, **kwargs)\n", " File \"/usr/local/lib/python2.7/dist-packages/plotly/graph_objs/graph_objs.py\", line 312, in __init__\n", " self.validate()\n", " File \"/usr/local/lib/python2.7/dist-packages/plotly/graph_objs/graph_objs.py\", line 600, in validate\n", " notes=notes)\n", "PlotlyDictKeyError: Invalid key, 'nonsense', for class, 'Figure'.\n", "\n", "Run 'help(plotly.graph_objs.Figure)' for more information.\n", "\n", "Path To Error:\n", "['nonsense']\n", "\n", "Additional Notes:\n", "Couldn't find uses for key: 'nonsense'\n", "\n", "\n", "\n" ] } ], "prompt_number": 21 }, { "cell_type": "markdown", "metadata": {}, "source": [ "so, which keys are accepted? call `help`! also check out [https://plot.ly/python/reference/](https://plot.ly/python/reference/)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "help(fig['layout'])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on Layout in module plotly.graph_objs.graph_objs object:\n", "\n", "class Layout(PlotlyDict)\n", " | A dictionary-like object containing specification of the layout of a plotly\n", " | figure.\n", " | \n", " | Online examples:\n", " | \n", " | https://plot.ly/python/figure-labels/\n", " | https://plot.ly/python/axes/\n", " | https://plot.ly/python/bar-charts/\n", " | https://plot.ly/python/log-plot/\n", " | \n", " | Parent key:\n", " | \n", " | layout\n", " | \n", " | Quick method reference:\n", " | \n", " | Layout.update(changes)\n", " | Layout.strip_style()\n", " | Layout.get_data()\n", " | Layout.to_graph_objs()\n", " | Layout.validate()\n", " | Layout.to_string()\n", " | Layout.force_clean()\n", " | \n", " | Valid keys:\n", " | \n", " | title [required=False] (value=a string):\n", " | The title of the figure.\n", " | \n", " | titlefont [required=False] (value=Font object | dictionary-like object):\n", " | Links a dictionary-like object describing the font settings of the\n", " | figure's title.\n", " | \n", " | For more, run `help(plotly.graph_objs.Font)`\n", " | \n", " | font [required=False] (value=Font object | dictionary-like object):\n", " | Links a dictionary-like object describing the global font settings\n", " | for this figure (e.g. all axis titles and labels).\n", " | \n", " | For more, run `help(plotly.graph_objs.Font)`\n", " | \n", " | showlegend [required=False] (value=a boolean: True | False):\n", " | Toggle whether or not the legend will be shown in this figure.\n", " | \n", " | autosize [required=False] (value=a boolean: True | False):\n", " | Toggle whether or not the dimensions of the figure are automatically\n", " | picked by Plotly. Plotly picks figure's dimensions as a function of\n", " | your machine's display resolution. Once 'autosize' is set to False,\n", " | the figure's dimensions can be set with 'width' and 'height'.\n", " | \n", " | width [required=False] (value=number: x > 0):\n", " | Sets the width in pixels of the figure you are generating.\n", " | \n", " | height [required=False] (value=number: x > 0):\n", " | Sets the height in pixels of the figure you are generating.\n", " | \n", " | xaxis [required=False] (value=XAxis object | dictionary-like object):\n", " | Links a dictionary-like object describing an x-axis (i.e. an\n", " | horizontal axis). The first XAxis object can be entered into\n", " | 'layout' by linking it to 'xaxis' OR 'xaxis1', both keys are\n", " | identical to Plotly. To create references other than x-axes, you\n", " | need to define them in 'layout' using keys 'xaxis2', 'xaxis3' and so\n", " | on. Note that in 3D plots, XAxis objects must be linked from a Scene\n", " | object.\n", " | \n", " | For more, run `help(plotly.graph_objs.XAxis)`\n", " | \n", " | yaxis [required=False] (value=YAxis object | dictionary-like object):\n", " | Links a dictionary-like object describing an y-axis (i.e. an\n", " | vertical axis). The first YAxis object can be entered into 'layout'\n", " | by linking it to 'yaxis' OR 'yaxis1', both keys are identical to\n", " | Plotly. To create references other than y-axes, you need to define\n", " | them in 'layout' using keys 'yaxis2', 'yaxis3' and so on. Note that\n", " | in 3D plots, YAxis objects must be linked from a Scene object.\n", " | \n", " | For more, run `help(plotly.graph_objs.YAxis)`\n", " | \n", " | legend [required=False] (value=Legend object | dictionary-like object):\n", " | Links a dictionary-like object containing the legend parameters for\n", " | this figure.\n", " | \n", " | For more, run `help(plotly.graph_objs.Legend)`\n", " | \n", " | annotations [required=False] (value=Annotations object | list-like\n", " | object of one or several dictionary-like object):\n", " | Links a list-like object that contains one or multiple annotation\n", " | dictionary-like objects.\n", " | \n", " | For more, run `help(plotly.graph_objs.Annotations)`\n", " | \n", " | margin [required=False] (value=Margin object | dictionary-like object):\n", " | Links a dictionary-like object containing the margin parameters for\n", " | this figure.\n", " | \n", " | For more, run `help(plotly.graph_objs.Margin)`\n", " | \n", " | paper_bgcolor [required=False] (value=a string describing color):\n", " | Sets the color of the figure's paper (i.e. area representing the\n", " | canvas of the figure).\n", " | \n", " | Examples:\n", " | 'green' | 'rgb(0, 255, 0)' | 'rgba(0, 255, 0, 0.3)' |\n", " | 'hsl(120,100%,50%)' | 'hsla(120,100%,50%,0.3)' | '#434F1D'\n", " | \n", " | plot_bgcolor [required=False] (value=a string describing color):\n", " | Sets the background color of the plot (i.e. the area laying inside\n", " | this figure's axes.\n", " | \n", " | Examples:\n", " | 'green' | 'rgb(0, 255, 0)' | 'rgba(0, 255, 0, 0.3)' |\n", " | 'hsl(120,100%,50%)' | 'hsla(120,100%,50%,0.3)' | '#434F1D'\n", " | \n", " | hovermode [required=False] (value='closest' | 'x' | 'y'):\n", " | Sets this figure's behavior when a user hovers over it. When set to\n", " | 'x', all data sharing the same 'x' coordinate will be shown on\n", " | screen with corresponding trace labels. When set to 'y' all data\n", " | sharing the same 'y' coordinates will be shown on the screen with\n", " | corresponding trace labels. When set to 'closest', information about\n", " | the data point closest to where the viewer is hovering will appear.\n", " | \n", " | dragmode [required=False] (value='zoom' | 'pan' | 'rotate' (in 3D\n", " | plots)):\n", " | Sets this figure's behavior when a user preforms a mouse 'drag' in\n", " | the plot area. When set to 'zoom', a portion of the plot will be\n", " | highlighted, when the viewer exits the drag, this highlighted\n", " | section will be zoomed in on. When set to 'pan', data in the plot\n", " | will move along with the viewers dragging motions. A user can always\n", " | depress the 'shift' key to access the whatever functionality has not\n", " | been set as the default. In 3D plots, the default drag mode is\n", " | 'rotate' which rotates the scene.\n", " | \n", " | separators [required=False] (value=a two-character string):\n", " | Sets the decimal (the first character) and thousands (the second\n", " | character) separators to be displayed on this figure's tick labels\n", " | and hover mode. This is meant for internationalization purposes. For\n", " | example, if 'separator' is set to ', ', then decimals are separated\n", " | by commas and thousands by spaces. One may have to set\n", " | 'exponentformat' to 'none' in the corresponding axis object(s) to\n", " | see the effects.\n", " | \n", " | barmode [required=False] (value='stack' | 'group' | 'overlay'):\n", " | For bar and histogram plots only. This sets how multiple bar objects\n", " | are plotted together. In other words, this defines how bars at the\n", " | same location appear on the plot. If set to 'stack' the bars are\n", " | stacked on top of one another. If set to 'group', the bars are\n", " | plotted next to one another, centered around the shared location. If\n", " | set to 'overlay', the bars are simply plotted over one another, you\n", " | may need to set the opacity to see this.\n", " | \n", " | bargap [required=False] (value=number: x in [0, 1)):\n", " | For bar and histogram plots only. Sets the gap between bars (or sets\n", " | of bars) at different locations.\n", " | \n", " | bargroupgap [required=False] (value=number: x in [0, 1)):\n", " | For bar and histogram plots only. Sets the gap between bars in the\n", " | same group. That is, when multiple bar objects are plotted and share\n", " | the same locations, this sets the distance between bars at each\n", " | location.\n", " | \n", " | boxmode [required=False] (value='overlay' | 'group'):\n", " | For box plots only. Sets how groups of box plots appear. If set to\n", " | 'overlay', a group of boxes will be plotted directly on top of one\n", " | another at their specified location. If set to 'group', the boxes\n", " | will be centered around their shared location, but they will not\n", " | overlap.\n", " | \n", " | boxgap [required=False] (value=number: x in [0, 1)):\n", " | For box plots only. Sets the gap between boxes at different\n", " | locations (i.e. x-labels). If there are multiple boxes at a single\n", " | x-label, then this sets the gap between these sets of boxes.For\n", " | example, if 0, then there is no gap between boxes. If 0.25, then\n", " | this gap occupies 25% of the available space and the box width (or\n", " | width of the set of boxes) occupies the remaining 75%.\n", " | \n", " | boxgroupgap [required=False] (value=number: x in [0, 1)):\n", " | For box plots only. Sets the gap between boxes in the same group,\n", " | where a group is the set of boxes with the same location (i.e.\n", " | x-label). For example, if 0, then there is no gap between boxes. If\n", " | 0.25, then this gap occupies 25% of the available space and the box\n", " | width occupies the remaining 75%.\n", " | \n", " | radialaxis [required=False] (value=RadialAxis object | dictionary-like\n", " | object):\n", " | Links a dictionary-like object describing the radial axis in a polar\n", " | plot.\n", " | \n", " | For more, run `help(plotly.graph_objs.RadialAxis)`\n", " | \n", " | angularaxis [required=False] (value=AngularAxis object | dictionary-like\n", " | object):\n", " | Links a dictionary-like object describing the angular axis in a\n", " | polar plot.\n", " | \n", " | For more, run `help(plotly.graph_objs.AngularAxis)`\n", " | \n", " | scene [required=False] (value=Scene object | dictionary-like object):\n", " | Links a dictionary-like object describing a scene in a 3D plot. The\n", " | first Scene object can be entered into 'layout' by linking it to\n", " | 'scene' OR 'scene1', both keys are identical to Plotly. Link\n", " | subsequent Scene objects using 'scene2', 'scene3', etc.\n", " | \n", " | For more, run `help(plotly.graph_objs.Scene)`\n", " | \n", " | direction [required=False] (value='clockwise' | 'counterclockwise'):\n", " | For polar plots only. Sets the direction corresponding to positive\n", " | angles.\n", " | \n", " | orientation [required=False] (value=number: x in [-360, 360]):\n", " | For polar plots only. Rotates the entire polar by the given angle.\n", " | \n", " | hidesources [required=False] (value=a boolean: True | False):\n", " | Toggle whether or not an annotation citing the data source is placed\n", " | at the bottom-right corner of the figure.This key has an effect only\n", " | on graphs that have been generated from forked graphs from plot.ly.\n", " | \n", " | Method resolution order:\n", " | Layout\n", " | PlotlyDict\n", " | __builtin__.dict\n", " | __builtin__.object\n", " | \n", " | Methods defined here:\n", " | \n", " | __init__(self, *args, **kwargs)\n", " | \n", " | force_clean(self, caller=True)\n", " | Attempts to convert to graph_objs and call force_clean() on values.\n", " | \n", " | Calling force_clean() on a Layout will ensure that the object is\n", " | valid and may be sent to plotly. This process will also remove any\n", " | entries that end up with a length == 0.\n", " | \n", " | Careful! This will delete any invalid entries *silently*.\n", " | \n", " | This method differs from the parent (PlotlyDict) method in that it\n", " | must check for an infinite number of possible axis keys, i.e. 'xaxis',\n", " | 'xaxis1', 'xaxis2', 'xaxis3', etc. Therefore, it cannot make a call\n", " | to super...\n", " | \n", " | to_graph_objs(self, caller=True)\n", " | Walk obj, convert dicts and lists to plotly graph objs.\n", " | \n", " | For each key in the object, if it corresponds to a special key that\n", " | should be associated with a graph object, the ordinary dict or list\n", " | will be reinitialized as a special PlotlyDict or PlotlyList of the\n", " | appropriate `kind`.\n", " | \n", " | to_string(self, level=0, indent=4, eol='\\n', pretty=True, max_chars=80)\n", " | Returns a formatted string showing graph_obj constructors.\n", " | \n", " | Example:\n", " | \n", " | print(obj.to_string())\n", " | \n", " | Keyword arguments:\n", " | level (default = 0) -- set number of indentations to start with\n", " | indent (default = 4) -- set indentation amount\n", " | eol (default = '\\n') -- set end of line character(s)\n", " | pretty (default = True) -- curtail long list output with a '...'\n", " | max_chars (default = 80) -- set max characters per line\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from PlotlyDict:\n", " | \n", " | __setitem__(self, key, value)\n", " | \n", " | get_data(self)\n", " | Returns the JSON for the plot with non-data elements stripped.\n", " | \n", " | get_ordered(self, caller=True)\n", " | \n", " | strip_style(self)\n", " | Strip style from the current representation.\n", " | \n", " | All PlotlyDicts and PlotlyLists are guaranteed to survive the\n", " | stripping process, though they made be left empty. This is allowable.\n", " | \n", " | Keys that will be stripped in this process are tagged with\n", " | `'type': 'style'` in graph_objs_meta.json.\n", " | \n", " | This process first attempts to convert nested collections from dicts\n", " | or lists to subclasses of PlotlyList/PlotlyDict. This process forces\n", " | a validation, which may throw exceptions.\n", " | \n", " | Then, each of these objects call `strip_style` on themselves and so\n", " | on, recursively until the entire structure has been validated and\n", " | stripped.\n", " | \n", " | update(self, dict1=None, **dict2)\n", " | Update current dict with dict1 and then dict2.\n", " | \n", " | This recursively updates the structure of the original dictionary-like\n", " | object with the new entries in the second and third objects. This\n", " | allows users to update with large, nested structures.\n", " | \n", " | Note, because the dict2 packs up all the keyword arguments, you can\n", " | specify the changes as a list of keyword agruments.\n", " | \n", " | Examples:\n", " | # update with dict\n", " | obj = Layout(title='my title', xaxis=XAxis(range=[0,1], domain=[0,1]))\n", " | update_dict = dict(title='new title', xaxis=dict(domain=[0,.8]))\n", " | obj.update(update_dict)\n", " | obj\n", " | {'title': 'new title', 'xaxis': {'range': [0,1], 'domain': [0,.8]}}\n", " | \n", " | # update with list of keyword arguments\n", " | obj = Layout(title='my title', xaxis=XAxis(range=[0,1], domain=[0,1]))\n", " | obj.update(title='new title', xaxis=dict(domain=[0,.8]))\n", " | obj\n", " | {'title': 'new title', 'xaxis': {'range': [0,1], 'domain': [0,.8]}}\n", " | \n", " | This 'fully' supports duck-typing in that the call signature is\n", " | identical, however this differs slightly from the normal update\n", " | method provided by Python's dictionaries.\n", " | \n", " | validate(self, caller=True)\n", " | Recursively check the validity of the keys in a PlotlyDict.\n", " | \n", " | The valid keys constitute the entries in each object\n", " | dictionary in graph_objs_meta.json\n", " | \n", " | The validation process first requires that all nested collections be\n", " | converted to the appropriate subclass of PlotlyDict/PlotlyList. Then,\n", " | each of these objects call `validate` and so on, recursively,\n", " | until the entire object has been validated.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from PlotlyDict:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from __builtin__.dict:\n", " | \n", " | __cmp__(...)\n", " | x.__cmp__(y) <==> cmp(x,y)\n", " | \n", " | __contains__(...)\n", " | D.__contains__(k) -> True if D has a key k, else False\n", " | \n", " | __delitem__(...)\n", " | x.__delitem__(y) <==> del x[y]\n", " | \n", " | __eq__(...)\n", " | x.__eq__(y) <==> x==y\n", " | \n", " | __ge__(...)\n", " | x.__ge__(y) <==> x>=y\n", " | \n", " | __getattribute__(...)\n", " | x.__getattribute__('name') <==> x.name\n", " | \n", " | __getitem__(...)\n", " | x.__getitem__(y) <==> x[y]\n", " | \n", " | __gt__(...)\n", " | x.__gt__(y) <==> x>y\n", " | \n", " | __iter__(...)\n", " | x.__iter__() <==> iter(x)\n", " | \n", " | __le__(...)\n", " | x.__le__(y) <==> x<=y\n", " | \n", " | __len__(...)\n", " | x.__len__() <==> len(x)\n", " | \n", " | __lt__(...)\n", " | x.__lt__(y) <==> x x!=y\n", " | \n", " | __repr__(...)\n", " | x.__repr__() <==> repr(x)\n", " | \n", " | __sizeof__(...)\n", " | D.__sizeof__() -> size of D in memory, in bytes\n", " | \n", " | clear(...)\n", " | D.clear() -> None. Remove all items from D.\n", " | \n", " | copy(...)\n", " | D.copy() -> a shallow copy of D\n", " | \n", " | fromkeys(...)\n", " | dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n", " | v defaults to None.\n", " | \n", " | get(...)\n", " | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.\n", " | \n", " | has_key(...)\n", " | D.has_key(k) -> True if D has a key k, else False\n", " | \n", " | items(...)\n", " | D.items() -> list of D's (key, value) pairs, as 2-tuples\n", " | \n", " | iteritems(...)\n", " | D.iteritems() -> an iterator over the (key, value) items of D\n", " | \n", " | iterkeys(...)\n", " | D.iterkeys() -> an iterator over the keys of D\n", " | \n", " | itervalues(...)\n", " | D.itervalues() -> an iterator over the values of D\n", " | \n", " | keys(...)\n", " | D.keys() -> list of D's keys\n", " | \n", " | pop(...)\n", " | D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n", " | If key is not found, d is returned if given, otherwise KeyError is raised\n", " | \n", " | popitem(...)\n", " | D.popitem() -> (k, v), remove and return some (key, value) pair as a\n", " | 2-tuple; but raise KeyError if D is empty.\n", " | \n", " | setdefault(...)\n", " | D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D\n", " | \n", " | values(...)\n", " | D.values() -> list of D's values\n", " | \n", " | viewitems(...)\n", " | D.viewitems() -> a set-like object providing a view on D's items\n", " | \n", " | viewkeys(...)\n", " | D.viewkeys() -> a set-like object providing a view on D's keys\n", " | \n", " | viewvalues(...)\n", " | D.viewvalues() -> an object providing a view on D's values\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from __builtin__.dict:\n", " | \n", " | __hash__ = None\n", " | \n", " | __new__ = \n", " | T.__new__(S, ...) -> a new object with type S, a subtype of T\n", "\n" ] } ], "prompt_number": 22 }, { "cell_type": "code", "collapsed": false, "input": [ "fig['layout']['title'] = 'two subplots'" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 23 }, { "cell_type": "markdown", "metadata": {}, "source": [ "`fig.append_trace` is a helper function for binding trace objects to axes. need some help? call `help`!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "help(fig.append_trace)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on method append_trace in module plotly.graph_objs.graph_objs:\n", "\n", "append_trace(self, trace, row, col) method of plotly.graph_objs.graph_objs.Figure instance\n", " Helper function to add a data traces to your figure\n", " that is bound to axes at the row, col index.\n", " \n", " The row, col index is generated from figures created with\n", " plotly.tools.make_subplots and can be viewed with Figure.print_grid.\n", " \n", " Example:\n", " # stack two subplots vertically\n", " fig = tools.make_subplots(rows=2)\n", " \n", " This is the format of your plot grid:\n", " [ (1,1) x1,y1 ]\n", " [ (2,1) x2,y2 ]\n", " \n", " fig.append_trace(Scatter(x=[1,2,3], y=[2,1,2]), 1, 1)\n", " fig.append_trace(Scatter(x=[1,2,3], y=[2,1,2]), 2, 1)\n", " \n", " Arguments:\n", " \n", " trace (plotly trace object):\n", " The data trace to be bound.\n", " \n", " row (int):\n", " Subplot row index on the subplot grid (see Figure.print_grid)\n", " \n", " col (int):\n", " Subplot column index on the subplot grid (see Figure.print_grid)\n", "\n" ] } ], "prompt_number": 24 }, { "cell_type": "code", "collapsed": false, "input": [ "fig.append_trace(Scatter(x=[1,2,3], y=[2,1,2], name='top trace'), row=1, col=1) # (row, col) match with the subplot arrangment that was printed out\n", "fig.append_trace(Scatter(x=[1,2,3], y=[2,1,2], name='bottom trace'), row=2, col=1)\n", "print fig" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "{'data': [{'name': 'top trace', 'yaxis': 'y1', 'xaxis': 'x1', 'y': [2, 1, 2], 'x': [1, 2, 3], 'type': u'scatter'}, {'name': 'bottom trace', 'yaxis': 'y2', 'xaxis': 'x2', 'y': [2, 1, 2], 'x': [1, 2, 3], 'type': u'scatter'}], 'layout': {'yaxis1': {'domain': [0.575, 1.0], 'anchor': 'x1'}, 'yaxis2': {'domain': [0.0, 0.425], 'anchor': 'x2'}, 'xaxis2': {'domain': [0.0, 1.0], 'anchor': 'y2'}, 'xaxis1': {'domain': [0.0, 1.0], 'anchor': 'y1'}, 'title': 'two subplots'}}\n" ] } ], "prompt_number": 25 }, { "cell_type": "code", "collapsed": false, "input": [ "print fig.to_string()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Figure(\n", " data=Data([\n", " Scatter(\n", " x=[1, 2, 3],\n", " y=[2, 1, 2],\n", " name='top trace',\n", " xaxis='x1',\n", " yaxis='y1'\n", " ),\n", " Scatter(\n", " x=[1, 2, 3],\n", " y=[2, 1, 2],\n", " name='bottom trace',\n", " xaxis='x2',\n", " yaxis='y2'\n", " )\n", " ]),\n", " layout=Layout(\n", " title='two subplots',\n", " xaxis1=XAxis(\n", " domain=[0.0, 1.0],\n", " anchor='y1'\n", " ),\n", " xaxis2=XAxis(\n", " domain=[0.0, 1.0],\n", " anchor='y2'\n", " ),\n", " yaxis1=YAxis(\n", " domain=[0.575, 1.0],\n", " anchor='x1'\n", " ),\n", " yaxis2=YAxis(\n", " domain=[0.0, 0.425],\n", " anchor='x2'\n", " )\n", " )\n", ")\n" ] } ], "prompt_number": 26 }, { "cell_type": "markdown", "metadata": {}, "source": [ "see the two Scatter traces in `fig['data']` above? we just inserted those!\n", "\n", "to view this graph, send it over to your plotly account" ] }, { "cell_type": "code", "collapsed": false, "input": [ "py.iplot(fig, filename='subplot example')" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "" ], "metadata": {}, "output_type": "pyout", "prompt_number": 27, "text": [ "" ] } ], "prompt_number": 27 }, { "cell_type": "markdown", "metadata": {}, "source": [ "now take a look at the examples above. in each case, we're just specifying a subplot arrangment and appending traces to the subplot coordinates that were printed\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Questions? , [@plotlygraphs](https://twitter.com/plotlygraphs)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from IPython.display import display, HTML\n", "import urllib2\n", "url = 'https://raw.githubusercontent.com/plotly/python-user-guide/master/custom.css'\n", "display(HTML(urllib2.urlopen(url).read()))" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "\n", "\n" ], "metadata": {}, "output_type": "display_data", "text": [ "" ] } ], "prompt_number": 28 }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 28 } ], "metadata": {} } ] }