25  Faceting

Faceting draws a pose as several panels: one panel for each category of a column, or one panel for each of several columns. Panels side by side make it easy to compare patterns across groups.

A facet over the categories of a column is a mapping: :col and :row are aesthetics, and pj/facet is the call that writes one. Because the facet is a mapping, it reaches into a composite, a cell can override the facet it inherits, and several columns under :col unite into one distinction. A facet over columns is written beside the mapping rather than in it. A grid can draw the categories of a column in one direction and a list of columns in the other.

(ns plotje-book.faceting
  (:require
   ;; Tablecloth -- dataset manipulation
   [tablecloth.api :as tc]
   ;; Rdatasets -- standard datasets
   [scicloj.metamorph.ml.rdatasets :as rdatasets]
   ;; Kindly -- notebook rendering protocol
   [scicloj.kindly.v4.kind :as kind]
   ;; Plotje -- composable plotting
   [scicloj.plotje.api :as pj]))

A Panel per Category

pj/facet splits a pose into panels by one categorical column, one panel for each category. By default the panels run across, in one row:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width {:color :species})
    (pj/facet :species))
sepal widthsepal lengthspeciessetosaversicolorvirginica682.02.53.03.54.04.56868setosaversicolorvirginica

Each species gets its own panel with a strip label on top. Scales are shared by default – all panels use the same x and y range, making direct comparison easy.

Ordering the panels

The panels follow the order in which the data holds the categories. A :domain on :col orders them instead, as a :domain on an axis orders its categories, and one on :row orders the rows of panels:

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy)
    (pj/facet :drv)
    (pj/scale :col {:domain ["r" "f" "4"]}))
hwydispl24615202530354045246246rf4

The panels, the categories of an axis and the entries of a legend follow one rule: the order the data holds them in, unless a :domain says otherwise. Colouring by the faceted column and giving both scales the same :domain lists the legend in the order of the panels:

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy {:color :drv})
    (pj/facet :drv)
    (pj/scale :col {:domain ["r" "f" "4"]})
    (pj/scale :color {:domain ["r" "f" "4"]}))
hwydispldrvrf424615202530354045246246rf4

A category the :domain leaves out still draws its panel, after the listed ones, and a name the :domain lists that the data does not hold draws no panel. Both cases print a warning:

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy)
    (pj/facet :drv)
    (pj/scale :col {:domain ["r" "f" "4" "x"]}))
hwydispl24615202530354045246246rf4

Wrapping the panels into rows

A column with many categories gives many narrow panels in one row. :cols in the map given to pj/facet after the column gives the number of panels across, and the panels continue on further rows, each under its strip. Here the seven classes of cars are drawn in rows of four:

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy)
    (pj/facet :class {:cols 4}))
203040compactmidsizesuv2462seater246203040minivan246pickup246subcompactdisplhwy

The panels still share both axes. Each column of panels is ticked once on :x, below its lowest panel.

Panels in one column, with :row

{:row :species} puts the panels down, in one column:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width {:color :species})
    (pj/facet {:row :species}))
sepal widthsepal lengthspeciessetosaversicolorvirginica2342344.55.05.56.06.57.07.58.0234setosaversicolorvirginica

A grid of two categories, with :col and :row

{:col ... :row ...} splits by two columns – the column under :col gives a column of panels for each of its values, the column under :row a row of panels:

(-> (rdatasets/reshape2-tips)
    (pj/lay-point :total-bill :tip {:color :sex})
    (pj/facet {:col :smoker :row :sex}))
tiptotal billsexFemaleMale51020405102040NoYesFemaleMale

Row labels appear on the right, column labels on top. A strip prints the category alone, so in this grid nothing on the plot says which strips are values of smoker and which of sex. The plot option {:strip-labels :both} prints the column’s name before each value:

(-> (rdatasets/reshape2-tips)
    (pj/lay-point :total-bill :tip {:color :sex})
    (pj/facet {:col :smoker :row :sex} {:strip-labels :both}))
tiptotal billsexFemaleMale51020405102040smoker: Nosmoker: Yessex: Femalesex: Male

A Panel per Column

pj/facet given a map of columns draws a panel for each column. Under :x the panels run across, each with one of the columns on its :x axis; under :y they run down, each with one of the columns on its :y axis. With no layer written, each panel draws the layer type inferred from its columns – here a histogram of each column:

(-> (rdatasets/datasets-iris)
    (pj/pose {:color :species})
    (pj/facet {:x [:sepal-length :sepal-width :petal-length]}))
countsepal length680246810121416countsepal width234024681012141618countpetal length2460510152025speciessetosaversicolorvirginica

A layer that names none of the facet’s columns is drawn in every panel. Name the column the panels have in common on the pose, and leave the other column to the facet:

(-> (rdatasets/ggplot2-mpg)
    (pj/pose {:x :displ})
    (pj/lay-smooth {:color "black"})
    (pj/facet {:y [:hwy :cty]}))
hwy15202530cty1.52.02.53.03.54.04.55.05.56.06.57.01416182022displ

A layer that names one of the facet’s columns is drawn only in the panel of that column. A panel left with no layer draws the layer type inferred from its columns – here a scatter of :displ against :cty beside the smooth of :hwy. The layer’s columns say where it is drawn – see Rule LP2 in Pose Rules. To draw the smooth in every panel, leave :y off the layer and name :x on the pose.

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-smooth :displ :hwy {:color "black"})
    (pj/facet {:y [:hwy :cty]}))
hwy15202530cty1.52.02.53.03.54.04.55.05.56.06.57.0102030displ

Grids Crossing Categories and Columns

A grid compares along two directions at once: species across and measurements down, or every measurement against every other. Every grid is one pj/facet call with a map under :col and :row, and each of the two entries is one of the two kinds of facet this chapter has shown – a column of categories, as in {:col :species}, or a map of columns, as in {:y [:hwy :cty]}. The grid has a panel for every pair of a value across and a value down.

under :col under :row the grid
a column of categories a column of categories categories by categories, {:col :smoker :row :sex} above
a column of categories a map of columns each category across, each column down
a map of columns a column of categories each column across, each category down
a map of columns a map of columns each column against each column – a scatter plot matrix when the two lists are the same

Categories crossed with columns

Here the species run across and two measurements run down, each drawn against :sepal-length:

(-> (rdatasets/datasets-iris)
    (pj/pose {:x :sepal-length})
    pj/lay-point
    (pj/facet {:col :species :row {:y [:sepal-width :petal-width]}}))
234680126868sepal lengthsetosaversicolorvirginicasepal widthpetal width

The grid may also be written as two calls, one facet over the categories and one over the columns, in either order: (-> pose (pj/facet {:y [...]}) (pj/facet :species)). The categories go into the pose’s mapping and the columns under its :facet, and the two are crossed when the pose is drawn. When both directions are taken, a third facet reports an error that suggests a colour or pj/arrange instead.

Scatter plot matrix

A scatter plot matrix (SPLOM) draws every column of a list against every column of the same list, to show all their pairwise relationships at once. The same list under :col, on :x, and under :row, on :y, gives the matrix, and the panel of a column against itself draws that one column, as a histogram. The histogram is drawn within the column’s own range, so it shares its row’s :y axis and the row’s tick labels stand at the left edge; its bar heights are relative, with no count axis:

(-> (rdatasets/datasets-iris)
    (pj/pose {:color :species})
    (pj/facet {:col {:x [:sepal-length :sepal-width :petal-length]}
               :row {:y [:sepal-length :sepal-width :petal-length]}})
    pj/lay-point)
6823468246234246sepal lengthsepal widthpetal lengthsepal lengthsepal widthpetal lengthspeciessetosaversicolorvirginica

pj/matrix writes this facet: (pj/matrix data cols) crosses a list of columns with itself, and the pose it returns is the one pj/facet returns for the map above.

(-> (rdatasets/datasets-iris)
    (pj/pose {:color :species})
    (pj/matrix [:sepal-length :sepal-width :petal-length])
    pj/lay-point)
6823468246234246sepal lengthsepal widthpetal lengthsepal lengthsepal widthpetal lengthspeciessetosaversicolorvirginica

Two different lists cross the same way: {:col {:x xs} :row {:y ys}}, or (pj/matrix data xs ys), draws each column of xs against each column of ys. Written without :col and :row, pj/facet given {:x xs :y ys} pairs the columns one by one instead, a panel per pair, as Layers on different columns, faceted shows below. A list of pairs given to pj/pose or to a pj/lay-* call is not read this way: it reports an error naming pj/arrange and pj/matrix. The Relationships chapter builds scatter plot matrices with more layers.

A facet over categories is a mapping

The panel aesthetics :col and :row draw each value of a column in a separate panel, labelled by a strip. The :color aesthetic tells marks apart by color within one panel instead. They are documented here, where they are written, rather than beside the keys of a layer’s mapping, because no pj/lay-* call accepts one.

(kind/table
 {:column-names [:aesthetic :what-it-reads]
  :row-vectors (mapv (fn [[k doc]] [k doc])
                     (sort-by (comp str key) pj/panel-aesthetic-docs))})
aesthetic what-it-reads
col A column of the pose's data, or a vector of them, giving each value a panel of its own, laid out across. A vector unites the columns into a compound key, so a panel is drawn for each combination the data holds. Written by (pj/facet my-pose col), and by (pj/facet my-pose {:col col :row ...}) for a grid, where the other entry may be categories or a map of columns.
row A column of the pose's data, or a vector of them, giving each value a panel of its own, laid out down. The same readings as :col. Written by (pj/facet my-pose {:row col}), and by (pj/facet my-pose {:col ... :row col}) for a grid, where the other entry may be categories or a map of columns.

pj/facet writes :col into the pose’s mapping. Here is the plot, and then the pose that draws it.

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/facet :species))
sepal widthsepal length682.02.53.03.54.04.56868setosaversicolorvirginica
(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/facet :species)
    kind/pprint)
{:layers
 [{:layer-type :point, :mapping {:x :sepal-length, :y :sepal-width}}],
 :data
 https://vincentarelbundock.github.io/Rdatasets/csv/datasets/iris.csv [150 6]:

| :rownames | :sepal-length | :sepal-width | :petal-length | :petal-width |  :species |
|----------:|--------------:|-------------:|--------------:|-------------:|-----------|
|         1 |           5.1 |          3.5 |           1.4 |          0.2 |    setosa |
|         2 |           4.9 |          3.0 |           1.4 |          0.2 |    setosa |
|         3 |           4.7 |          3.2 |           1.3 |          0.2 |    setosa |
|         4 |           4.6 |          3.1 |           1.5 |          0.2 |    setosa |
|         5 |           5.0 |          3.6 |           1.4 |          0.2 |    setosa |
|         6 |           5.4 |          3.9 |           1.7 |          0.4 |    setosa |
|         7 |           4.6 |          3.4 |           1.4 |          0.3 |    setosa |
|         8 |           5.0 |          3.4 |           1.5 |          0.2 |    setosa |
|         9 |           4.4 |          2.9 |           1.4 |          0.2 |    setosa |
|        10 |           4.9 |          3.1 |           1.5 |          0.1 |    setosa |
|       ... |           ... |          ... |           ... |          ... |       ... |
|       140 |           6.9 |          3.1 |           5.4 |          2.1 | virginica |
|       141 |           6.7 |          3.1 |           5.6 |          2.4 | virginica |
|       142 |           6.9 |          3.1 |           5.1 |          2.3 | virginica |
|       143 |           5.8 |          2.7 |           5.1 |          1.9 | virginica |
|       144 |           6.8 |          3.2 |           5.9 |          2.3 | virginica |
|       145 |           6.7 |          3.3 |           5.7 |          2.5 | virginica |
|       146 |           6.7 |          3.0 |           5.2 |          2.3 | virginica |
|       147 |           6.3 |          2.5 |           5.0 |          1.9 | virginica |
|       148 |           6.5 |          3.0 |           5.2 |          2.0 | virginica |
|       149 |           6.2 |          3.4 |           5.4 |          2.3 | virginica |
|       150 |           5.9 |          3.0 |           5.1 |          1.8 | virginica |
,
 :mapping {:col :species}}

(pj/facet my-pose {:row col}) writes :row instead, and (pj/facet my-pose {:col col-a :row col-b}) writes both.

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy)
    (pj/facet {:col :drv :row :cyl})
    kind/pprint)
{:layers [{:layer-type :point, :mapping {:x :displ, :y :hwy}}],
 :data
 https://vincentarelbundock.github.io/Rdatasets/csv/ggplot2/mpg.csv [234 12]:

| :rownames | :manufacturer |     :model | :displ | :year | :cyl |     :trans | :drv | :cty | :hwy | :fl |     :class |
|----------:|---------------|------------|-------:|------:|-----:|------------|------|-----:|-----:|-----|------------|
|         1 |          audi |         a4 |    1.8 |  1999 |    4 |   auto(l5) |    f |   18 |   29 |   p |    compact |
|         2 |          audi |         a4 |    1.8 |  1999 |    4 | manual(m5) |    f |   21 |   29 |   p |    compact |
|         3 |          audi |         a4 |    2.0 |  2008 |    4 | manual(m6) |    f |   20 |   31 |   p |    compact |
|         4 |          audi |         a4 |    2.0 |  2008 |    4 |   auto(av) |    f |   21 |   30 |   p |    compact |
|         5 |          audi |         a4 |    2.8 |  1999 |    6 |   auto(l5) |    f |   16 |   26 |   p |    compact |
|         6 |          audi |         a4 |    2.8 |  1999 |    6 | manual(m5) |    f |   18 |   26 |   p |    compact |
|         7 |          audi |         a4 |    3.1 |  2008 |    6 |   auto(av) |    f |   18 |   27 |   p |    compact |
|         8 |          audi | a4 quattro |    1.8 |  1999 |    4 | manual(m5) |    4 |   18 |   26 |   p |    compact |
|         9 |          audi | a4 quattro |    1.8 |  1999 |    4 |   auto(l5) |    4 |   16 |   25 |   p |    compact |
|        10 |          audi | a4 quattro |    2.0 |  2008 |    4 | manual(m6) |    4 |   20 |   28 |   p |    compact |
|       ... |           ... |        ... |    ... |   ... |  ... |        ... |  ... |  ... |  ... | ... |        ... |
|       224 |    volkswagen | new beetle |    2.0 |  1999 |    4 | manual(m5) |    f |   21 |   29 |   r | subcompact |
|       225 |    volkswagen | new beetle |    2.0 |  1999 |    4 |   auto(l4) |    f |   19 |   26 |   r | subcompact |
|       226 |    volkswagen | new beetle |    2.5 |  2008 |    5 | manual(m5) |    f |   20 |   28 |   r | subcompact |
|       227 |    volkswagen | new beetle |    2.5 |  2008 |    5 |   auto(s6) |    f |   20 |   29 |   r | subcompact |
|       228 |    volkswagen |     passat |    1.8 |  1999 |    4 | manual(m5) |    f |   21 |   29 |   p |    midsize |
|       229 |    volkswagen |     passat |    1.8 |  1999 |    4 |   auto(l5) |    f |   18 |   29 |   p |    midsize |
|       230 |    volkswagen |     passat |    2.0 |  2008 |    4 |   auto(s6) |    f |   19 |   28 |   p |    midsize |
|       231 |    volkswagen |     passat |    2.0 |  2008 |    4 | manual(m6) |    f |   21 |   29 |   p |    midsize |
|       232 |    volkswagen |     passat |    2.8 |  1999 |    6 |   auto(l5) |    f |   16 |   26 |   p |    midsize |
|       233 |    volkswagen |     passat |    2.8 |  1999 |    6 | manual(m5) |    f |   18 |   26 |   p |    midsize |
|       234 |    volkswagen |     passat |    3.6 |  2008 |    6 |   auto(s6) |    f |   17 |   26 |   p |    midsize |
,
 :mapping {:col :drv, :row :cyl}}

Any mapping value may be written as a map naming its source, and a panel aesthetic is no exception. These two draw the same plot.

(-> (rdatasets/datasets-iris)
    (pj/pose {:x :sepal-length :y :sepal-width :col {:column :species}})
    (pj/lay-point))
sepal widthsepal length682.02.53.03.54.04.56868setosaversicolorvirginica

What the scope rules give

Mappings flow downward: a mapping written on a pose reaches every layer and every sub-pose below it, and a sub-pose that writes its own key overrides what it inherits. A panel aesthetic is a mapping, so all of that applies to faceting.

A composite can be faceted

A facet written on an arranged pose divides every cell of it.

(-> (pj/arrange [[(pj/pose (rdatasets/datasets-iris) :sepal-length :sepal-width)]
                 [(pj/pose (rdatasets/datasets-iris) :petal-length :petal-width)]])
    (pj/lay-point)
    (pj/facet :species)
    (pj/options {:width 700 :height 560}))
sepal widthsepal length56782.02.53.03.54.04.556785678setosaversicolorvirginicapetal widthpetal length2460.00.51.01.52.02.5246246setosaversicolorvirginica

Two cells, three species, six panels. pj/arrange takes one vector per row, so [[a] [b]] stacks the two cells and each has the full width for its three panels.

A facet over columns is not a mapping, so it does not reach into a composite: pj/facet given an arranged pose and a map of columns reports an error naming the spellings that draw – a facet on each cell, or the columns arranged as cells.

One cell can be faceted differently from another

A cell that writes its own :col overrides the one it inherits, which is the rule for every mapping key. Here the top cell is divided by species and the bottom cell is not divided at all.

(-> (pj/arrange [[(-> (pj/pose (rdatasets/datasets-iris) :sepal-length :sepal-width)
                      (pj/facet :species))]
                 [(pj/pose (rdatasets/datasets-iris) :petal-length :petal-width)]])
    (pj/lay-point)
    (pj/options {:width 700 :height 560}))
sepal widthsepal length56782.02.53.03.54.04.556785678setosaversicolorvirginicapetal widthpetal length1.01.52.02.53.03.54.04.55.05.56.06.57.00.00.51.01.52.02.5

Three panels in the top row and one in the bottom row.

Layers on different columns, faceted

The layers of a pose share its panel, so a pose whose layers name different columns draws one panel, and faceting it by a column draws one panel per value:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/lay-point :petal-length :petal-width)
    (pj/facet :species)
    (pj/options {:width 900 :height 480}))
sepal width, petal widthsepal length, petal lengthsepal length / sepal widthpetal length / petal width24680.00.51.01.52.02.53.03.54.04.524682468setosaversicolorvirginica

To give each pair of columns a row of its own as well, cross the categories with the columns in one pj/facet call. Each layer is drawn in the row of the columns it names. Two calls, one facet over the pairs and one over :species, write the same pose in either order:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/lay-point :petal-length :petal-width)
    (pj/facet {:col :species
               :row {:x [:sepal-length :petal-length]
                     :y [:sepal-width :petal-width]}})
    (pj/options {:width 900 :height 480}))
sepal length56782.02.53.03.54.04.5sepal length5678sepal length5678petal length2460.00.51.01.52.02.5petal length246petal length246setosaversicolorvirginicasepal widthpetal width

A marginal follows the division

pj/marginal builds a fresh leaf rather than a descendant, so the scope rules do not reach it on their own. It carries the panel aesthetics across itself, giving a faceted main panel a marginal above each of its panels. The strip label is drawn once per column, at the top.

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/facet :species)
    (pj/marginal :top)
    (pj/options {:width 900 :height 480}))
density0.00.51.0setosaversicolorvirginicasepal width56782.02.53.03.54.04.556785678sepal length

Several columns as one key

Under some aesthetics, several columns in a vector are one distinction made of those columns united – a compound key. That is what {:group [:a :b]} means, and the panel aesthetics read a vector the same way. pj/compound-key-aesthetics names the aesthetics that read a vector of columns as a compound key. Plotje checks a vector against this set, so under an aesthetic outside the set, several columns where one goes report an error rather than being united:

(pj/compound-key-aesthetics)
#{:group :col :row}

The table below holds three of the four combinations of :part and :dimension: there is no petal width row.

(def measures
  (tc/dataset {:part      ["sepal" "sepal" "sepal" "sepal" "petal" "petal"]
               :dimension ["length" "length" "width" "width" "length" "length"]
               :t         [1 2 1 2 1 2]
               :v         [1.0 2.0 1.5 2.5 2.0 3.0]}))
measures

_unnamed [6 4]:

:part :dimension :t :v
sepal length 1 1.0
sepal length 2 2.0
sepal width 1 1.5
sepal width 2 2.5
petal length 1 2.0
petal length 2 3.0

:color is outside the set, because a mark has one color. A vector written on :color reports an error rather than uniting its columns:

(try
  (-> measures
      (pj/lay-point :t :v {:color [:part :dimension]}))
  (catch clojure.lang.ExceptionInfo e
    (ex-message e)))
"pj/lay-point :color was given several columns, [:part :dimension]. Several columns where one goes are read as several series, which belongs on :x or :y -- the aesthetics that name what a mark is drawn from. Written there, the key column the pivot invents is mapped to :color on its own."

A compound facet draws one panel per combination the data holds, labelled by each column’s value in turn.

(-> measures
    (pj/lay-point :t :v)
    (pj/facet [:part :dimension]))
vt121231212sepal / lengthsepal / widthpetal / length

{:col :part :row :dimension} crosses two distinctions and fills the rectangle, so the combination the data does not hold is drawn as an empty panel.

(-> measures
    (pj/lay-point :t :v)
    (pj/facet {:col :part :row :dimension}))
vt12312123no data12sepalpetallengthwidth

Free Scales (Independent Axis Ranges)

By default the panels of a facet share each axis on which they draw the same column. In a facet over categories every panel draws the same columns, so the panels share both axis ranges, and a mark at the same height stands for the same value in every panel. In a facet over columns, the panels drawing different columns keep an axis range each. The :share-scales option names the axes the panels share, as a set. An axis left out of the set is fitted to the rows of each panel. A map, as in {:y :all}, shares an axis between panels that draw different columns, as the Series chapter shows. An axis the map leaves out is not shared: on a facet over columns, {:y :all} alone leaves :x unshared, so every panel labels its own :x ticks, and {:x :same-column :y :all} keeps :x shared among the panels drawing the same column, labelled once.

Both axes shared – the default, written out:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width {:color :species})
    (pj/facet :species)
    (pj/options {:share-scales #{:x :y}}))
sepal widthsepal lengthspeciessetosaversicolorvirginica682.02.53.03.54.04.56868setosaversicolorvirginica

Only :x shared – each panel has its own y range:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width {:color :species})
    (pj/facet :species)
    (pj/options {:share-scales #{:x}}))
sepal widthsepal lengthspeciessetosaversicolorvirginica682.22.42.62.83.03.23.43.63.84.04.24.4682.02.22.42.62.83.03.23.4682.22.42.62.83.03.23.43.63.8setosaversicolorvirginica

#{:y} shares :y and fits :x to each panel, and #{} fits both axes to each panel. In a grid of categories too, an axis left out of the set is fitted to each panel, where ggplot2’s facet_grid(scales = "free_y") fits it to each row of panels.

The options of a faceted plot may also be written in the facet call, in a map after the column. pj/facet passes that map to pj/options, except for :cols, which only pj/facet takes. So for every other option the two spellings build the same pose:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width {:color :species})
    (pj/facet :species {:share-scales #{:x}}))
sepal widthsepal lengthspeciessetosaversicolorvirginica682.22.42.62.83.03.23.43.63.84.04.24.4682.02.22.42.62.83.03.23.4682.22.42.62.83.03.23.43.63.8setosaversicolorvirginica

A shared axis covers what the panels sharing it draw, and is padded once. So the panels of a facet read on the axes the same plot has when it is not split:

(let [whole (-> (rdatasets/datasets-iris)
                (pj/lay-point :sepal-length :sepal-width))
      domains (fn [pose]
                (->> pose
                     pj/plan
                     :panels
                     (mapv (juxt :x-domain :y-domain))))]
  {:not-split (first (domains whole))
   :each-panel (distinct (domains (pj/facet whole :species)))})
{:not-split [[4.12 8.08] [1.88 4.5200000000000005]],
 :each-panel ([[4.12 8.08] [1.88 4.5200000000000005]])}

A shared axis of categories lists every category the panels hold, in the order of the data, so a category sits at the same place in every panel. The panels of a faceted histogram share their count axis.

pj/arrange takes the same option for its cells, where it can also say which columns share an axis; see Composition and, for what a shared axis covers, What a Shared Axis Covers.

Appearance Aesthetics Across Panels

:share-scales is about the axes, and the axes alone. A :size or :alpha column is read against every value the plot holds, whichever panel a mark sits in, so one value is one size everywhere and the legend explains every panel at once.

Below, the left panel’s values run from 1 to 3 and the right panel’s from 4 to 10, so every mark on the left is smaller than every mark on the right:

(def per-panel
  {:g ["L" "L" "L" "R" "R" "R"]
   :x [1 2 3 1 2 3]
   :y [1 1 1 1 1 1]
   :n [1 2 3 4 7 10]})
(-> per-panel
    (pj/lay-point :x :y {:size :n})
    (pj/facet :g))
yxn246810123012123LR

A :color or :shape column is read against the whole data too. The legend lists the categories in the order the rows of the data hold them, whichever panel a row is drawn in, so a category has the colour it has in the same plot drawn without the facet. Below, the first panel holds some of the classes and not others, and the legend is the legend of the unfaceted plot:

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy {:color :class})
    (pj/facet :drv))
hwydisplclasscompactmidsizesuv2seaterminivanpickupsubcompact24615202530354045246246f4r

A :domain sets that one extent. Given more room than the data needs, no mark reaches either end of the range:

(-> per-panel
    (pj/lay-point :x :y {:size :n})
    (pj/facet :g)
    (pj/scale :size {:domain [0 20]}))
yxn05101520123012123LR

A panel aesthetic on a layer is an error

A facet divides every layer of the pose alike, and a panel aesthetic is read from a pose’s mapping and not from a layer’s, so a panel aesthetic belongs on the pose. Written in a pj/lay-* mapping, a panel aesthetic reports an error, and the message names the places to write it instead.

(try
  (-> (rdatasets/datasets-iris)
      (pj/lay-point :sepal-length :sepal-width {:col :species})
      pj/plan)
  (catch Exception e (ex-message e)))
"A panel aesthetic col was written in a layer's mapping. A facet divides every layer of the pose, and a panel aesthetic is read from a pose's mapping and not from a layer's, so write it on the pose: (pj/facet pose :species), or in the pose's mapping. On a composite, write it on the cell whose panels it divides."

A second facet in the same direction on one pose reports an error rather than replacing the first. A facet written on a cell of a composite overrides the facet the cell inherits, by the scope rules.

(try
  (-> (rdatasets/datasets-iris)
      (pj/lay-point :sepal-length :sepal-width)
      (pj/facet :species)
      (pj/facet :sepal-length))
  (catch Exception e (ex-message e)))
"pj/facet was given :sepal-length for :col, which this pose already facets by :species. A pose divides its panels once per direction: write the other direction, (pj/facet pose {:row :sepal-length}), which with the earlier facet draws a grid, or leave out the earlier facet and write one compound key in its place -- (pj/facet pose [:species :sepal-length])."

The map given to pj/facet says where the panels come from, and takes no other key. A plot option written inside it reports an error, and the message says to write the option in a map of its own, after the first:

(try
  (-> (rdatasets/datasets-iris)
      (pj/lay-point :sepal-length :sepal-width)
      (pj/facet {:col :species :share-scales #{:x}}))
  (catch Exception e (ex-message e)))
"pj/facet was given {:col :species, :share-scales #{:x}}, and the map has unexpected key(s): [:share-scales]. It takes [:col :row]. :share-scales is a plot option: write it in a map of its own after this one, as in (pj/facet pose {...} {:share-scales ...})."

Where a facet’s column holds so many values that each panel would be narrower than the smallest panel size, the error names the column and the number of its values, and suggests wrapping the panels with :cols and a height the rows fit in, as in β€œWrapping the panels into rows” above:

(try
  (-> (rdatasets/ggplot2-mpg)
      (pj/lay-point :displ :hwy)
      (pj/facet :model)
      pj/plan)
  (catch Exception e (ex-message e)))
"Each panel would be 15 wide, which is below the smallest panel size, 20. The plot's width, 600, less 38 for its labels and legend (38 for the y axis labels), leaves 562 for 38 columns of panels. Increase :width, set :panel-width directly, or lower :min-panel-size for a sparkline-sized plot. The panels are those of a facet by :model, which holds 38 values and draws them in one row. For several rows of panels, give the facet across a number of panels per row with :cols, and the plot a height its rows fit in: (pj/facet pose :model {:cols 4 :height 1200})."

Facet or Arrange

pj/facet and pj/arrange both draw several panels, and many plots can be written with either call. Which call fits depends on where the panels come from. A facet generates its panels from one pose: a panel for each category of a column, or a panel for each column the facet names, all drawn from the same data with the same layers. An arrangement lists its cells, and each cell is a pose of its own, with its own mapping and layers. The cells read the data the arrangement is given, or each holds data of its own.

Cells that each hold data of their own share no axis. Here three cells each hold the rows of one kind of drive, and each :y axis covers only its own cell’s rows:

(pj/arrange (vec (for [drive ["4" "f" "r"]]
                   (-> (rdatasets/ggplot2-mpg)
                       (tc/select-rows #(= drive (:drv %)))
                       (pj/lay-point :displ :hwy)
                       (pj/options {:title drive})))))
4hwydispl246121416182022242628fhwydispl24202530354045rhwydispl46161820222426

{:share-scales #{:y}} in the arrangement’s options gives the three cells one :y axis, as the Shared Scales section of the Composition chapter shows.

A facet over :drv divides one dataset, so its three panels share both axes:

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy)
    (pj/facet :drv))
hwydispl24615202530354045246246f4r

A facet over categories draws what an arrangement of :where cells draws: one cell per category, each holding the whole data and a :where, the row filter that keeps the rows of that category. Written out by hand, the cells draw the same plot as the facet:

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy)
    (pj/arrange [{:where {:drv "f"}} {:where {:drv "4"}} {:where {:drv "r"}}]))
hwydispl24615202530354045246246f4r

The cells are parts of the arrangement’s data, so they share both axes, as the panels of the facet do – the cells holding data of their own, above, share none.

The plots agree and the poses do not: the arrangement holds its cells under :poses, and the faceted pose holds no :poses. A layer added afterwards is drawn alike in both. Added to the facet, (pj/lay-point :displ :cty) draws in each of the three panels, in a second colour:

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy)
    (pj/facet :drv)
    (pj/lay-point :displ :cty))
hwy, ctydisplhwycty2461015202530354045246246f4r

Added to the arrangement, the same layer is drawn in each of the three cells, since no cell draws another column on :x or :y, and the plot is the facet’s:

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy)
    (pj/arrange [{:where {:drv "f"}} {:where {:drv "4"}} {:where {:drv "r"}}])
    (pj/lay-point :displ :cty))
hwy, ctydisplhwycty2461015202530354045246246f4r

The cells of an arrangement can also be plots of different kinds, which the panels of a facet cannot. Here a cell naming two columns draws a scatter, and a cell naming one column draws a histogram:

(pj/arrange (rdatasets/ggplot2-mpg) [{:x :displ :y :hwy} :hwy])
hwydispl24615202530354045counthwy203040010203040506070

An arrangement wraps its cells into rows with :cols, as a facet wraps its panels. {:cols 2} places the three :where cells in two columns, and draws what the facet by :drv given {:cols 2} draws. Each cell keeps its strip, and the cells still share both axes:

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy)
    (pj/arrange [{:where {:drv "f"}} {:where {:drv "4"}} {:where {:drv "r"}}]
                {:cols 2}))
203040f2464246203040rdisplhwy

So write pj/facet when the panels are parts of one plot: one dataset and the same layers, divided by the categories of a column or across columns. A facet also reaches every cell of an arrangement it is written on, as β€œA composite can be faceted” above shows. Write pj/arrange when the cells are different plots – different data, different layers, a dashboard – or when the layout needs what only a list of cells can say: an empty cell written nil, rows of different lengths, or one arrangement placed inside another. A layer holding data of its own is drawn whole in every panel of a facet, so a reference line computed for each category needs an arrangement, as Known Limitations says.

The Order of the Calls

pj/facet may be written anywhere in a pipeline. pj/options, pj/scale and pj/coord written before the facet give the pose they give written after it, and a layer added before or after the facet draws the same plot. These two pipelines write the same calls in different orders:

(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy)
    (pj/facet :drv)
    (pj/scale :y {:domain [0 50]})
    pj/lay-smooth)
hwydispl24605101520253035404550246246f4r
(-> (rdatasets/ggplot2-mpg)
    (pj/lay-point :displ :hwy)
    pj/lay-smooth
    (pj/scale :y {:domain [0 50]})
    (pj/facet :drv))
hwydispl24605101520253035404550246246f4r

The same holds under a facet over columns, where a layer added before or after the facet gives an equal pose.

Coming from ggplot2

A reader who knows ggplot2 looks for its faceting functions by name. Each has a Plotje spelling, or none:

ggplot2 Plotje
facet_wrap(~ drv) (pj/facet pose :drv), which draws the panels in one row
facet_wrap(~ class, ncol = 4) (pj/facet pose :class {:cols 4})
facet_grid(cyl ~ drv) (pj/facet pose {:col :drv :row :cyl})
facet_wrap(scales = "free") {:share-scales #{}} in the options map after the facet, which fits each panel to its own rows
facet_grid(scales = "free") {:share-scales #{}}, which fits :x and :y to each panel; ggplot2 fits :x to each column of panels and :y to each row, which has no Plotje spelling
facet_grid(scales = "free_y") {:share-scales #{:x}}, which fits :y to each panel rather than to each row
GGally::ggpairs(data, columns = cols) (pj/matrix data cols), which writes the facet {:col {:x cols} :row {:y cols}}: a scatter off the diagonal and a histogram on it
facet_grid(labeller = label_both) {:strip-labels :both} in the options map after the facet
facet_grid(margins = TRUE) no option; stack the data with a copy labelled "(all)", as below

Panels follow the order the data holds the values. ggplot2 sorts a text or numeric column and follows the levels of a factor, so facet_grid(cyl ~ drv) draws the cylinder rows in increasing order, where Plotje draws them in the order of the data; (pj/scale pose :col {:domain [...]}) plays the part of factor(levels = ...), as the section on ordering the panels shows.

ggplot2 Equivalents collects the ggplot2 spellings outside faceting – layers, scales, coordinates, labels – with the Plotje spelling of each.

A panel for all rows

ggplot2’s margins = TRUE adds a panel that draws every category together, so each panel can be compared with the whole. The same panel comes from the data: stack the dataset with a copy of itself whose facet column reads "(all)", and facet the stacked rows. The copy is the last value the data holds, so its panel comes last:

(let [mpg (rdatasets/ggplot2-mpg)]
  (-> (tc/concat mpg (tc/add-column mpg :drv "(all)"))
      (pj/lay-point :displ :hwy)
      (pj/facet :drv)))
hwydispl24615202530354045246246246f4r(all)

Each row is drawn twice, in its own panel and in the "(all)" panel. For a grid, stack a copy for each direction and one more for the corner, where both columns read "(all)".

Examples

Faceted plots of other kinds, each built from the ideas above.

Faceted Histogram

(-> (rdatasets/datasets-iris)
    (pj/lay-histogram :sepal-length {:color :species})
    (pj/facet :species))
countsepal lengthspeciessetosaversicolorvirginica6802468101214166868setosaversicolorvirginica

Faceted Regression

Layers compose with faceting – scatter plus regression per panel:

(-> (rdatasets/reshape2-tips)
    (pj/pose :total-bill :tip {:color :sex})
    pj/lay-point
    (pj/lay-smooth {:stat :linear-model})
    (pj/facet {:col :smoker :row :sex}))
tiptotal billsexFemaleMale51020405102040NoYesFemaleMale

Faceted Bar Chart

Five bars total across the three island panels: Adelie appears on every island, while Gentoo lives only on Biscoe and Chinstrap only on Dream. Empty species-island combinations produce no bar.

(-> (rdatasets/palmerpenguins-penguins)
    (pj/lay-bar :species {:color :species})
    (pj/facet :island)
    (pj/options {:width 800}))
countspeciesspeciesAdelieGentooChinstrapAdelieGentooChinstrap020406080100120AdelieGentooChinstrapAdelieGentooChinstrapTorgersenBiscoeDream

Labels and Faceting

pj/options works with faceted plots:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width {:color :species})
    (pj/facet :species)
    (pj/options {:title "Iris by Species"
                 :x-label "Sepal Length (cm)" :y-label "Sepal Width (cm)"}))
Iris by SpeciesSepal Width (cm)Sepal Length (cm)speciessetosaversicolorvirginica682.02.53.03.54.04.56868setosaversicolorvirginica

See Also

What’s Next

  • Series – reading several columns by name rather than by value
  • Troubleshooting – common issues and how to fix them
  • API Reference – complete function listing with docstrings
source: notebooks/plotje_book/faceting.clj