plotnine.facets.facet_wrap

class plotnine.facets.facet_wrap(facets=None, nrow=None, ncol=None, scales='fixed', shrink=True, labeller='label_value', as_table=True, drop=True, dir='h')[source]

Wrap 1D Panels onto 2D surface

Parameters
facetsformula | tuple | list

Variables to groupby and plot on different panels. If a formula is used it should be right sided, e.g '~ a + b', ('a', 'b')

nrowint, optional

Number of rows

ncolint, optional

Number of columns

scalesstr in ['fixed', 'free', 'free_x', 'free_y']

Whether x or y scales should be allowed (free) to vary according to the data on each of the panel. Default is 'fixed'.

shrinkbool

Whether to shrink the scales to the output of the statistics instead of the raw data. Default is True.

labellerstr | function

How to label the facets. If it is a str, it should be one of 'label_value' 'label_both' or 'label_context'. Default is 'label_value'

as_tablebool

If True, the facets are laid out like a table with the highest values at the bottom-right. If False the facets are laid out like a plot with the highest value a the top-right. Default it True.

dropbool

If True, all factor levels not used in the data will automatically be dropped. If False, all factor levels will be shown, regardless of whether or not they appear in the data. Default is True.

dirstr in ['h', 'v']

Direction in which to layout the panels. h for horizontal and v for vertical.

Examples

[1]:
import pandas as pd

from plotnine import *
from plotnine.data import *

%matplotlib inline

Facet wrap

facet_wrap() creates a collection of plots (facets), where each plot is differentiated by the faceting variable. These plots are wrapped into a certain number of columns or rows as specified by the user.

[2]:
mpg.head()
[2]:
manufacturer model displ year cyl trans drv cty hwy fl class
0 audi a4 1.8 1999 4 auto(l5) f 18 29 p compact
1 audi a4 1.8 1999 4 manual(m5) f 21 29 p compact
2 audi a4 2.0 2008 4 manual(m6) f 20 31 p compact
3 audi a4 2.0 2008 4 auto(av) f 21 30 p compact
4 audi a4 2.8 1999 6 auto(l5) f 16 26 p compact

Basic scatter plot:

[3]:
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + labs(x='displacement', y='horsepower')
)
../_images/facet_wra_4_0.png
[3]:
<ggplot: (7015175863)>

Facet a discrete variable using facet_wrap():

[5]:
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_wrap('class')
    + labs(x='displacement', y='horsepower')
)
../_images/facet_wra_6_0.png
[5]:
<ggplot: (-9223372029842314082)>

Control the number of rows and columns with the options nrow and ncol:

[6]:
# Selecting the number of columns to display
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_wrap('class',
                 ncol = 4 # change the number of columns
                )
    + labs(x='displacement', y='horsepower')
)
../_images/facet_wra_8_0.png
[6]:
<ggplot: (7012658920)>
[7]:
# Selecting the number of rows to display

(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_wrap('class',
                 nrow = 4 # change the number of columns
                )
    + labs(x='displacement', y='horsepower')
)
../_images/facet_wra_9_0.png
[7]:
<ggplot: (-9223372029841385321)>

To change the plot order of the facets, reorder the levels of the faceting variable in the data.

[8]:
# re-order categories
mpg['class'] = mpg['class'].cat.reorder_categories(['pickup', 'suv','minivan','midsize','compact','subcompact','2seater'])
[9]:
# facet plot with reorded drv category
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_wrap('class')
    + labs(x='displacement', y='horsepower')
)
../_images/facet_wra_12_0.png
[9]:
<ggplot: (-9223372029841281662)>

Ordinarily the facets are arranged horizontally (left-to-right from top to bottom). However if you would prefer a vertical layout (facets are arranged top-to-bottom, from left to right) use the dir option:

[16]:
# Facet plot with vertical layout
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_wrap('class'
                , dir = 'v' # change to a vertical layout
                )
    + labs(x='displacement', y='horsepower')
)
../_images/facet_wra_14_0.png
[16]:
<ggplot: (7012804879)>

You can choose if the scale of x- and y-axes are fixed or variable. Set the scales argument to free-y, free_x or free for a free scales on the y-axis, x-axis or both axes respectively. You may need to add spacing between the facets to ensure axis ticks and values are easy to read.

A fixed scale is the default and does not need to be specified.

[11]:
# facet plot with free scales
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_wrap('class'
                , scales = 'free_y'           # set scales so y-scale varies with the data
                )
    + theme(subplots_adjust={'wspace': 0.25}) # add spaceing between facets to make y-axis ticks visible
    + labs(x='displacement', y='horsepower')
)
../_images/facet_wra_16_0.png
[11]:
<ggplot: (7013219939)>

You can add additional information to your facet labels, by using the labeller argument within the facet_wrap() command. Below we use labeller = 'label_both' to include the column name in the facet label.

[12]:
# facet plot with labeller
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_wrap('class', labeller = 'label_both')
    + labs(x='displacement', y='horsepower')
)
../_images/facet_wra_18_0.png
[12]:
<ggplot: (7012775502)>

You can add two discrete variables to a facet:

[13]:
# add additional column for plotting exercise
mpg["transmission"] = mpg['trans'].map(lambda x: "auto" if "auto" in x else "man" if "man" in x else "")
[14]:
# inspect new column transmission which identifies cars as having an automatic or manual transmission
mpg.head()
[14]:
manufacturer model displ year cyl trans drv cty hwy fl class transmission
0 audi a4 1.8 1999 4 auto(l5) f 18 29 p compact auto
1 audi a4 1.8 1999 4 manual(m5) f 21 29 p compact man
2 audi a4 2.0 2008 4 manual(m6) f 20 31 p compact man
3 audi a4 2.0 2008 4 auto(av) f 21 30 p compact auto
4 audi a4 2.8 1999 6 auto(l5) f 16 26 p compact auto
[15]:
# facet plot with two variables on one facet
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_wrap('~ class + transmission') # use ~ + to add additional faceting variables
    + labs(x='displacement', y='horsepower')
)
../_images/facet_wra_22_0.png
[15]:
<ggplot: (-9223372029842321099)>