plotnine.facets.facet_grid

class plotnine.facets.facet_grid(facets, margins=False, scales='fixed', space='fixed', shrink=True, labeller='label_value', as_table=True, drop=True)[source]

Wrap 1D Panels onto 2D surface

Parameters
facetsstr | tuple | list

A formula with the rows (of the tabular display) on the LHS and the columns (of the tabular display) on the RHS; the dot in the formula is used to indicate there should be no faceting on this dimension (either row or column). If a tuple/list is used, it must of size two, the elements of which must be strings or lists. If string formula is not processed as you may expect, use tuple/list. For example, the follow two specifications are equivalent:

'func(var4) ~ func(var1+var3) + func(var2)'
['func(var4)', ('func(var1+var3)', 'func(var2)')]

There may be cases where you cannot use a use a pure string formula, e.g.:

['var4', ('var1+var3', 'var2')]
scalesstr in ['fixed', 'free', 'free_x', 'free_y']

Whether x or y scales should be allowed (free) to vary according to the data along rows or columns. Default is 'fixed', the same scales for all the panels.

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

Whether the x or y sides of the panels should have the size. It also depends to the scales parameter. Default is 'fixed'. This setting is not yet supported.

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.

Examples

[1]:
import pandas as pd

from plotnine import *
from plotnine.data import *

%matplotlib inline

Facet grid

facet_grid() is used to form a grid of plots, where the rows and columns of the grid are set by the faceting variables. It is useful for visualising two discrete variables.

[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_grid_4_0.png
[3]:
<ggplot: (-9223372029843189353)>

Facet a discrete variable into rows:

[4]:
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_grid('drv ~ .')
    + labs(x='displacement', y='horsepower')
)
../_images/facet_grid_6_0.png
[4]:
<ggplot: (-9223372029845903195)>

Facet a discrete variable into columns:

[5]:
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_grid('. ~ cyl')
    + labs(x='displacement', y='horsepower')
)
../_images/facet_grid_8_0.png
[5]:
<ggplot: (7009325565)>

Facet two discrete variables into rows and columns:

[6]:
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_grid('drv ~ cyl')
    + labs(x='displacement', y='horsepower')
)
../_images/facet_grid_10_0.png
[6]:
<ggplot: (-9223372029845518953)>

To change the plot order of the rows or columns in the facet grid, reorder the levels of the faceting variable in the data.

[7]:
# re-order categories
mpg['drv'] = mpg['drv'].cat.reorder_categories(['f', 'r','4'])
[8]:
# facet plot with reorded drv category
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_grid('drv ~ cyl')
    + labs(x='displacement', y='horsepower')
)
../_images/facet_grid_13_0.png
[8]:
<ggplot: (-9223372029843189269)>

You can choose if the scale of x- and y-axes are fixed or variable by using the scales argument within the facet_grid() command:

[9]:
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_grid('drv ~ .', scales = 'free')
    + labs(x='displacement', y='horsepower')
)
../_images/facet_grid_15_0.png
[9]:
<ggplot: (-9223372029843189339)>

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

[10]:
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_grid('drv ~ .', labeller = 'label_both')
    + labs(x='displacement', y='horsepower')
)
../_images/facet_grid_17_0.png
[10]:
<ggplot: (7011547624)>

You can add two discrete variables to a facet:

[11]:
# 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 "")
[12]:
# inspect new column transmission which identifies cars as having an automatic or manual transmission
mpg.head()
[12]:
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
[13]:
# facet plot with two variables on one facet
(
    ggplot(mpg, aes(x='displ', y='hwy'))
    + geom_point()
    + facet_grid('drv + transmission ~ .') # use + to add additional faceting variables
    + labs(x='displacement', y='horsepower')
)
../_images/facet_grid_21_0.png
[13]:
<ggplot: (7010302770)>

Facet labels can be rotated to make them easier to read using strip_text_y = element_text(angle = 0) for row labels within the theme() command (use strip_text_x = element_text(angle = 0) for column labels).

If the labels do not fit in the strip, adjust the width of the strip using strip_background_y for rows (use strip_background_x for columns). You may also need to adjust the text position so it fits in the strip: adjust the horizontal text position in the strip by specifying ha in element_text()(specify va in element_text() to adjust the vertical text position).

You can also change the colour of the strip by specifying color in element_text() .

[14]:
(
    ggplot(mpg, aes(x='drv', y='model'))
    + geom_point()
    + facet_grid('manufacturer ~ .', scales = 'free')
    + theme(strip_text_y = element_text(angle = 0,              # change facet text angle
                                        ha = 'left'             # change text alignment
                                       ),
            strip_background_y = element_text(color = '#969dff' # change background colour of facet background
                                              , width = 0.2     # adjust width of facet background to fit facet text
                                             ),
            figure_size=(6, 15)                                 # adjust width & height of figure to fit y-axis
           )
    + labs(x='displacement', y='')
)
../_images/facet_grid_23_0.png
[14]:
<ggplot: (7010676246)>