Show Sidebar Hide Sidebar

Facet and Trellis Plots in Python

How to make Facet and Trellis Plots in Python with Plotly.

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: Facet Grids and Trellis Plots are available in version 2.0.12+
Run pip install plotly --upgrade to update your Plotly version

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

Facet by Column¶

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.

In [2]:
import plotly.plotly as py
import plotly.figure_factory as ff

import pandas as pd
mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')

grid = ff.create_facet_grid(
    mpg,
    x='displ',
    y='cty',
    facet_col='cyl',
)

py.iplot(grid, filename='facet by col')
Out[2]:

Facet by Row¶

In [3]:
import plotly.plotly as py
import plotly.figure_factory as ff

import pandas as pd
mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')

grid = ff.create_facet_grid(
    mpg,
    x='displ',
    y='cty',
    facet_row='cyl',
    marker={'color': 'rgb(86, 7, 100)'},
)

py.iplot(grid, filename='facet by row')
Out[3]:

Facet by Row and Column¶

In [4]:
import plotly.plotly as py
import plotly.figure_factory as ff

import pandas as pd
mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')

grid = ff.create_facet_grid(
    mpg,
    x='displ',
    y='cty',
    facet_row='cyl',
    facet_col='drv',
    marker={'color': 'rgb(234, 239, 155)'},
)

py.iplot(grid, filename='facet by row and col')
Out[4]:

Color by Categorical Variable¶

In [5]:
import plotly.plotly as py
import plotly.figure_factory as ff

import pandas as pd
mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')

fig = ff.create_facet_grid(
    mtcars,
    x='mpg',
    y='wt',
    facet_col='cyl',
    color_name='cyl',
    color_is_cat=True,
)
py.iplot(fig, filename='facet - color by categorical variable')
Out[5]:

Custom Colormap¶

In [6]:
import plotly.plotly as py
import plotly.figure_factory as ff

import pandas as pd
tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')

fig = ff.create_facet_grid(
    tips,
    x='total_bill',
    y='tip',
    color_name='sex',
    show_boxes=False,
    marker={'size': 10, 'opacity': 1.0},
    colormap={'Male': 'rgb(165, 242, 242)', 'Female': 'rgb(253, 174, 216)'}
)
py.iplot(fig, filename='facet - custom colormap')
Out[6]:

Label Variable Name:Value¶

In [7]:
import plotly.plotly as py
import plotly.figure_factory as ff

import pandas as pd
mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')

fig = ff.create_facet_grid(
    mtcars,
    x='mpg',
    y='wt',
    facet_col='cyl',
    facet_col_labels='name',
    facet_row_labels='name',
)
py.iplot(fig, filename='facet - label variable name')
Out[7]:

Custom Labels¶

In [8]:
import plotly.plotly as py
import plotly.figure_factory as ff

import pandas as pd
mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')

fig = ff.create_facet_grid(
    mtcars,
    x='wt',
    y='mpg',
    facet_col='cyl',
    facet_col_labels={4: '$2^2 = 4$', 6: '$\\frac{18}{3} = 6$', 8: '$2\cdot4 = 8$'},
    marker={'color': 'rgb(240, 100, 2)'},
)

py.iplot(fig, filename='facet - custom labels')
Out[8]:

Plot in 'ggplot2' style¶

To learn more about ggplot2, check out http://ggplot2.tidyverse.org/reference/facet_grid.html

In [9]:
import plotly.plotly as py
import plotly.figure_factory as ff

import pandas as pd
tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')

fig = ff.create_facet_grid(
    tips,
    x='total_bill',
    y='tip',
    facet_row='sex',
    facet_col='smoker',
    marker={'symbol': 'circle-open', 'size': 10},
    ggplot2=True
)
py.iplot(fig, filename='facet - ggplot2 style')
Out[9]:

Plot with 'scattergl' traces¶

In [10]:
import plotly.plotly as py
import plotly.figure_factory as ff

import pandas as pd
mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')

grid = ff.create_facet_grid(
    mpg,
    x='class',
    y='displ',
    trace_type='scattergl',
)

py.iplot(grid, filename='facet - scattergl')
Out[10]:

Plot with Histogram Traces¶

In [11]:
import plotly.plotly as py
import plotly.figure_factory as ff

import pandas as pd
tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')

fig = ff.create_facet_grid(
    tips,
    x='total_bill',
    y='tip',
    facet_row='sex',
    facet_col='smoker',
    trace_type='histogram',
)

py.iplot(fig, filename='facet - histogram traces')
Out[11]:

Other Trace Types¶

Facet Grids support scatter, scattergl, histogram, bar and box trace types. More trace types coming in the future.

In [13]:
import plotly.plotly as py
import plotly.figure_factory as ff

import pandas as pd
tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')

fig = ff.create_facet_grid(
    tips,
    y='tip',
    facet_row='sex',
    facet_col='smoker',
    trace_type='box',
)

py.iplot(fig, filename='facet - box traces')
Out[13]:

Reference¶

In [14]:
help(ff.create_facet_grid)
Help on function create_facet_grid in module plotly.figure_factory._facet_grid:

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)
    Returns figure for facet grid.
    
    :param (pd.DataFrame) df: the dataframe of columns for the facet grid.
    :param (str) x: the name of the dataframe column for the x axis data.
    :param (str) y: the name of the dataframe column for the y axis data.
    :param (str) facet_row: the name of the dataframe column that is used to
        facet the grid into row panels.
    :param (str) facet_col: the name of the dataframe column that is used to
        facet the grid into column panels.
    :param (str) color_name: the name of your dataframe column that will
        function as the colormap variable.
    :param (str|list|dict) colormap: the param that determines how the
        color_name column colors the data. If the dataframe contains numeric
        data, then a dictionary of colors will group the data categorically
        while a Plotly Colorscale name or a custom colorscale will treat it
        numerically. To learn more about colors and types of colormap, run
        `help(plotly.colors)`.
    :param (bool) color_is_cat: determines whether a numerical column for the
        colormap will be treated as categorical (True) or sequential (False).
            Default = False.
    :param (str|dict) facet_row_labels: set to either 'name' or a dictionary
        of all the unique values in the faceting row mapped to some text to
        show up in the label annotations. If None, labeling works like usual.
    :param (str|dict) facet_col_labels: set to either 'name' or a dictionary
        of all the values in the faceting row mapped to some text to show up
        in the label annotations. If None, labeling works like usual.
    :param (int) height: the height of the facet grid figure.
    :param (int) width: the width of the facet grid figure.
    :param (str) trace_type: decides the type of plot to appear in the
        facet grid. The options are 'scatter', 'scattergl', 'histogram',
        'bar', and 'box'.
        Default = 'scatter'.
    :param (str) scales: determines if axes have fixed ranges or not. Valid
        settings are 'fixed' (all axes fixed), 'free_x' (x axis free only),
        'free_y' (y axis free only) or 'free' (both axes free).
    :param (float) dtick_x: determines the distance between each tick on the
        x-axis. Default is None which means dtick_x is set automatically.
    :param (float) dtick_y: determines the distance between each tick on the
        y-axis. Default is None which means dtick_y is set automatically.
    :param (bool) show_boxes: draws grey boxes behind the facet titles.
    :param (bool) ggplot2: draws the facet grid in the style of `ggplot2`. See
        http://ggplot2.tidyverse.org/reference/facet_grid.html for reference.
        Default = False
    :param (int) binsize: groups all data into bins of a given length.
    :param (dict) kwargs: a dictionary of scatterplot arguments.
    
    Examples 1: One Way Faceting
    ```
    import plotly.plotly as py
    import plotly.figure_factory as ff
    
    import pandas as pd
    
    mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')
    
    fig = ff.create_facet_grid(
        mpg,
        x='displ',
        y='cty',
        facet_col='cyl',
    )
    py.iplot(fig, filename='facet_grid_mpg_one_way_facet')
    ```
    
    Example 2: Two Way Faceting
    ```
    import plotly.plotly as py
    import plotly.figure_factory as ff
    
    import pandas as pd
    
    mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')
    
    fig = ff.create_facet_grid(
        mpg,
        x='displ',
        y='cty',
        facet_row='drv',
        facet_col='cyl',
    )
    py.iplot(fig, filename='facet_grid_mpg_two_way_facet')
    ```
    
    Example 3: Categorical Coloring
    ```
    import plotly.plotly as py
    import plotly.figure_factory as ff
    
    import pandas as pd
    
    mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')
    
    fig = ff.create_facet_grid(
        mtcars,
        x='mpg',
        y='wt',
        facet_col='cyl',
        color_name='cyl',
        color_is_cat=True,
    )
    py.iplot(fig, filename='facet_grid_mpg_default_colors')
    ```
    
    Example 4: Sequential Coloring
    ```
    import plotly.plotly as py
    import plotly.figure_factory as ff
    
    import pandas as pd
    
    tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')
    
    fig = ff.create_facet_grid(
        tips,
        x='total_bill',
        y='tip',
        facet_row='sex',
        facet_col='smoker',
        color_name='size',
        colormap='Viridis',
    )
    py.iplot(fig, filename='facet_grid_tips_sequential_colors')
    ```
    
    Example 5: Custom labels
    ```
    import plotly.plotly as py
    import plotly.figure_factory as ff
    
    import pandas as pd
    
    mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')
    
    fig = ff.create_facet_grid(
        mtcars,
        x='wt',
        y='mpg',
        facet_col='cyl',
        facet_col_labels={4: "$\alpha$", 6: '$\beta$', 8: '$\sqrt[y]{x}$'},
    )
    
    py.iplot(fig, filename='facet_grid_mtcars_custom_labels')
    ```
    
    Example 6: Other Trace Type
    ```
    import plotly.plotly as py
    import plotly.figure_factory as ff
    
    import pandas as pd
    
    mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')
    
    fig = ff.create_facet_grid(
        mtcars,
        x='wt',
        facet_col='cyl',
        trace_type='histogram',
    )
    
    py.iplot(fig, filename='facet_grid_mtcars_other_trace_type')
    ```

Still need help?
Contact Us

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