{ "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: `Facet Grids and Trellis Plots` are available in version 2.0.12+
\n", "Run `pip install plotly --upgrade` to update your Plotly version" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'2.5.0'" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly\n", "plotly.__version__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Facet by Column\n", "A `facet grid` is a generalization of a scatterplot matrix where we can \"facet\" a row and/or column by another variable. Given some tabular data, stored in a `pandas.DataFrame`, we can plot one variable against another to form a regular scatter plot, _and_ we can pick a third faceting variable to form panels along the rows and/or columns to segment the data even further, forming a bunch of panels. We can also assign a coloring rule or a heatmap based on a color variable to color the plot." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import pandas as pd\n", "mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')\n", "\n", "fig = ff.create_facet_grid(\n", " mpg,\n", " x='displ',\n", " y='cty',\n", " facet_col='cyl',\n", ")\n", "\n", "py.iplot(fig, filename='facet by col')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Facet by Row" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import pandas as pd\n", "mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')\n", "\n", "fig = ff.create_facet_grid(\n", " mpg,\n", " x='displ',\n", " y='cty',\n", " facet_row='cyl',\n", " marker={'color': 'rgb(86, 7, 100)'},\n", ")\n", "\n", "py.iplot(fig, filename='facet by row')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Facet by Row and Column" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import pandas as pd\n", "mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')\n", "\n", "fig = ff.create_facet_grid(\n", " mpg,\n", " x='displ',\n", " y='cty',\n", " facet_row='cyl',\n", " facet_col='drv',\n", " marker={'color': 'rgb(234, 239, 155)'},\n", ")\n", "\n", "py.iplot(fig, filename='facet by row and col')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Color by Categorical Variable" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import pandas as pd\n", "mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')\n", "\n", "fig = ff.create_facet_grid(\n", " mtcars,\n", " x='mpg',\n", " y='wt',\n", " facet_col='cyl',\n", " color_name='cyl',\n", " color_is_cat=True,\n", ")\n", "py.iplot(fig, filename='facet - color by categorical variable')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Custom Colormap" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import pandas as pd\n", "tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')\n", "\n", "fig = ff.create_facet_grid(\n", " tips,\n", " x='total_bill',\n", " y='tip',\n", " color_name='sex',\n", " show_boxes=False,\n", " marker={'size': 10, 'opacity': 1.0},\n", " colormap={'Male': 'rgb(165, 242, 242)', 'Female': 'rgb(253, 174, 216)'}\n", ")\n", "py.iplot(fig, filename='facet - custom colormap')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Label Variable Name:Value" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import pandas as pd\n", "mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')\n", "\n", "fig = ff.create_facet_grid(\n", " mtcars,\n", " x='mpg',\n", " y='wt',\n", " facet_col='cyl',\n", " facet_col_labels='name',\n", " facet_row_labels='name',\n", ")\n", "py.iplot(fig, filename='facet - label variable name')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Custom Labels" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import pandas as pd\n", "mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')\n", "\n", "fig = ff.create_facet_grid(\n", " mtcars,\n", " x='wt',\n", " y='mpg',\n", " facet_col='cyl',\n", " facet_col_labels={4: '$2^2 = 4$', 6: '$\\\\frac{18}{3} = 6$', 8: '$2\\cdot4 = 8$'},\n", " marker={'color': 'rgb(240, 100, 2)'},\n", ")\n", "\n", "py.iplot(fig, filename='facet - custom labels')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Plot in 'ggplot2' style\n", "To learn more about ggplot2, check out http://ggplot2.tidyverse.org/reference/facet_grid.html" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import pandas as pd\n", "tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')\n", "\n", "fig = ff.create_facet_grid(\n", " tips,\n", " x='total_bill',\n", " y='tip',\n", " facet_row='sex',\n", " facet_col='smoker',\n", " marker={'symbol': 'circle-open', 'size': 10},\n", " ggplot2=True\n", ")\n", "py.iplot(fig, filename='facet - ggplot2 style')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Plot with 'scattergl' traces" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import pandas as pd\n", "mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')\n", "\n", "grid = ff.create_facet_grid(\n", " mpg,\n", " x='class',\n", " y='displ',\n", " trace_type='scattergl',\n", ")\n", "\n", "py.iplot(grid, filename='facet - scattergl')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Plot with Histogram Traces" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import pandas as pd\n", "tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')\n", "\n", "fig = ff.create_facet_grid(\n", " tips,\n", " x='total_bill',\n", " y='tip',\n", " facet_row='sex',\n", " facet_col='smoker',\n", " trace_type='histogram',\n", ")\n", "\n", "py.iplot(fig, filename='facet - histogram traces')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Other Trace Types\n", "Facet Grids support `scatter`, `scattergl`, `histogram`, `bar` and `box` trace types. More trace types coming in the future." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import pandas as pd\n", "tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')\n", "\n", "fig = ff.create_facet_grid(\n", " tips,\n", " y='tip',\n", " facet_row='sex',\n", " facet_col='smoker',\n", " trace_type='box',\n", ")\n", "\n", "py.iplot(fig, filename='facet - box traces')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Reference" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function create_facet_grid in module plotly.figure_factory._facet_grid:\n", "\n", "create_facet_grid(df, x=None, y=None, facet_row=None, facet_col=None, color_name=None, colormap=None, color_is_cat=False, facet_row_labels=None, facet_col_labels=None, height=None, width=None, trace_type='scatter', scales='fixed', dtick_x=None, dtick_y=None, show_boxes=True, ggplot2=False, binsize=1, **kwargs)\n", " Returns figure for facet grid.\n", " \n", " :param (pd.DataFrame) df: the dataframe of columns for the facet grid.\n", " :param (str) x: the name of the dataframe column for the x axis data.\n", " :param (str) y: the name of the dataframe column for the y axis data.\n", " :param (str) facet_row: the name of the dataframe column that is used to\n", " facet the grid into row panels.\n", " :param (str) facet_col: the name of the dataframe column that is used to\n", " facet the grid into column panels.\n", " :param (str) color_name: the name of your dataframe column that will\n", " function as the colormap variable.\n", " :param (str|list|dict) colormap: the param that determines how the\n", " color_name column colors the data. If the dataframe contains numeric\n", " data, then a dictionary of colors will group the data categorically\n", " while a Plotly Colorscale name or a custom colorscale will treat it\n", " numerically. To learn more about colors and types of colormap, run\n", " `help(plotly.colors)`.\n", " :param (bool) color_is_cat: determines whether a numerical column for the\n", " colormap will be treated as categorical (True) or sequential (False).\n", " Default = False.\n", " :param (str|dict) facet_row_labels: set to either 'name' or a dictionary\n", " of all the unique values in the faceting row mapped to some text to\n", " show up in the label annotations. If None, labeling works like usual.\n", " :param (str|dict) facet_col_labels: set to either 'name' or a dictionary\n", " of all the values in the faceting row mapped to some text to show up\n", " in the label annotations. If None, labeling works like usual.\n", " :param (int) height: the height of the facet grid figure.\n", " :param (int) width: the width of the facet grid figure.\n", " :param (str) trace_type: decides the type of plot to appear in the\n", " facet grid. The options are 'scatter', 'scattergl', 'histogram',\n", " 'bar', and 'box'.\n", " Default = 'scatter'.\n", " :param (str) scales: determines if axes have fixed ranges or not. Valid\n", " settings are 'fixed' (all axes fixed), 'free_x' (x axis free only),\n", " 'free_y' (y axis free only) or 'free' (both axes free).\n", " :param (float) dtick_x: determines the distance between each tick on the\n", " x-axis. Default is None which means dtick_x is set automatically.\n", " :param (float) dtick_y: determines the distance between each tick on the\n", " y-axis. Default is None which means dtick_y is set automatically.\n", " :param (bool) show_boxes: draws grey boxes behind the facet titles.\n", " :param (bool) ggplot2: draws the facet grid in the style of `ggplot2`. See\n", " http://ggplot2.tidyverse.org/reference/facet_grid.html for reference.\n", " Default = False\n", " :param (int) binsize: groups all data into bins of a given length.\n", " :param (dict) kwargs: a dictionary of scatterplot arguments.\n", " \n", " Examples 1: One Way Faceting\n", " ```\n", " import plotly.plotly as py\n", " import plotly.figure_factory as ff\n", " \n", " import pandas as pd\n", " \n", " mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')\n", " \n", " fig = ff.create_facet_grid(\n", " mpg,\n", " x='displ',\n", " y='cty',\n", " facet_col='cyl',\n", " )\n", " py.iplot(fig, filename='facet_grid_mpg_one_way_facet')\n", " ```\n", " \n", " Example 2: Two Way Faceting\n", " ```\n", " import plotly.plotly as py\n", " import plotly.figure_factory as ff\n", " \n", " import pandas as pd\n", " \n", " mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')\n", " \n", " fig = ff.create_facet_grid(\n", " mpg,\n", " x='displ',\n", " y='cty',\n", " facet_row='drv',\n", " facet_col='cyl',\n", " )\n", " py.iplot(fig, filename='facet_grid_mpg_two_way_facet')\n", " ```\n", " \n", " Example 3: Categorical Coloring\n", " ```\n", " import plotly.plotly as py\n", " import plotly.figure_factory as ff\n", " \n", " import pandas as pd\n", " \n", " mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')\n", " \n", " fig = ff.create_facet_grid(\n", " mtcars,\n", " x='mpg',\n", " y='wt',\n", " facet_col='cyl',\n", " color_name='cyl',\n", " color_is_cat=True,\n", " )\n", " py.iplot(fig, filename='facet_grid_mpg_default_colors')\n", " ```\n", " \n", " Example 4: Sequential Coloring\n", " ```\n", " import plotly.plotly as py\n", " import plotly.figure_factory as ff\n", " \n", " import pandas as pd\n", " \n", " tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')\n", " \n", " fig = ff.create_facet_grid(\n", " tips,\n", " x='total_bill',\n", " y='tip',\n", " facet_row='sex',\n", " facet_col='smoker',\n", " color_name='size',\n", " colormap='Viridis',\n", " )\n", " py.iplot(fig, filename='facet_grid_tips_sequential_colors')\n", " ```\n", " \n", " Example 5: Custom labels\n", " ```\n", " import plotly.plotly as py\n", " import plotly.figure_factory as ff\n", " \n", " import pandas as pd\n", " \n", " mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')\n", " \n", " fig = ff.create_facet_grid(\n", " mtcars,\n", " x='wt',\n", " y='mpg',\n", " facet_col='cyl',\n", " facet_col_labels={4: \"$\\alpha$\", 6: '$\\beta$', 8: '$\\sqrt[y]{x}$'},\n", " )\n", " \n", " py.iplot(fig, filename='facet_grid_mtcars_custom_labels')\n", " ```\n", " \n", " Example 6: Other Trace Type\n", " ```\n", " import plotly.plotly as py\n", " import plotly.figure_factory as ff\n", " \n", " import pandas as pd\n", " \n", " mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')\n", " \n", " fig = ff.create_facet_grid(\n", " mtcars,\n", " x='wt',\n", " facet_col='cyl',\n", " trace_type='histogram',\n", " )\n", " \n", " py.iplot(fig, filename='facet_grid_mtcars_other_trace_type')\n", " ```\n", "\n" ] } ], "source": [ "help(ff.create_facet_grid)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "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-9QI998-build\n", "Installing collected packages: publisher\n", " Found existing installation: publisher 0.11\n", " Uninstalling publisher-0.11:\n", " Successfully uninstalled publisher-0.11\n", " Running setup.py install for publisher ... \u001b[?25ldone\n", "\u001b[?25hSuccessfully installed publisher-0.11\n", "\u001b[33mYou are using pip version 9.0.1, however version 9.0.2 is available.\n", "You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/nbconvert.py:13: ShimWarning:\n", "\n", "The `IPython.nbconvert` package has been deprecated since IPython 4.0. You should import from nbconvert instead.\n", "\n", "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/publisher/publisher.py:53: UserWarning:\n", "\n", "Did you \"Save\" this notebook before running this command? Remember to save, always save.\n", "\n" ] } ], "source": [ "! pip install git+https://github.com/plotly/publisher.git --upgrade\n", "import publisher\n", "publisher.publish(\n", " 'facet-and-trellis-plots.ipynb', 'python/facet-plots/', 'Facet and Trellis Plots',\n", " 'How to make Facet and Trellis Plots in Python with Plotly.',\n", " title = 'Python Facet and Trellis Plots | plotly',\n", " redirect_from ='python/trellis-plots/',\n", " has_thumbnail='true', thumbnail='thumbnail/facet-trellis-thumbnail.jpg',\n", " language='python',\n", " display_as='statistical', order=10.2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "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": 1 }