8  Composition

Plotje’s poses let you combine whole plots into a single rendered image. A composite pose holds other poses and a layout; each sub-pose renders independently and the composite tiles them together.

This chapter walks through composition patterns from simple side-by-side arrangements to shared-scale marginal plots, using pj/arrange, pj/marginal and explicit composite-pose maps – compactly for simple cases, with a bit of literal map construction for nested layouts.

On a first read through the book you can skim or skip the later, deeper sections – Count and Density Axes, Cells Drawn Flipped, Cells That Line Up and Notes on the Current Implementation – and return when you build a composite that needs them.

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

Side-by-Side via pj/arrange

The simplest composite: two independent poses, placed next to each other. pj/arrange takes a vector of poses and returns a composite. Each sub-pose has its own data, mapping, layers, and options. Coming from R, this is the layout of patchwork’s p1 | p2 or cowplot’s plot_grid(p1, p2). Those draw a legend for each plot, while Plotje draws one shared legend, as patchwork does with plot_layout(guides = "collect").

(pj/arrange
 [(-> (rdatasets/datasets-iris) (pj/lay-point :sepal-length :sepal-width {:color :species}))
  (-> (rdatasets/datasets-iris) (pj/lay-point :petal-length :petal-width {:color :species}))])
sepal widthsepal length682.02.53.03.54.04.5petal widthpetal length2460.00.51.01.52.02.5speciessetosaversicolorvirginica

Pass {:cols 1} for a stacked arrangement (one column means each pose goes on its own row):

(pj/arrange
 [(-> (rdatasets/datasets-iris) (pj/lay-point :sepal-length :sepal-width {:color :species}))
  (-> (rdatasets/datasets-iris) (pj/lay-point :petal-length :petal-width {:color :species}))]
 {:cols 1})
sepal widthsepal length4.55.05.56.06.57.07.58.0234petal widthpetal length1234567012speciessetosaversicolorvirginica

A vector of vectors gives one row per inner vector. nil in place of a pose is a cell left empty: it keeps its place in the layout and draws nothing, so the other cells stay where they are.

(pj/arrange
 [[(-> (rdatasets/datasets-iris) (pj/lay-point :sepal-length :sepal-width {:color :species}))
   nil]
  [(-> (rdatasets/datasets-iris) (pj/lay-point :petal-length :sepal-width {:color :species}))
   (-> (rdatasets/datasets-iris) (pj/lay-point :petal-length :petal-width {:color :species}))]])
sepal widthsepal length68234sepal widthpetal length246234petal widthpetal length246012speciessetosaversicolorvirginica

pj/arrange also takes data first. Each cell is then written as the argument after the data in pj/pose is written: a mapping such as {:x :sepal-length :y :sepal-width} is a panel drawing those two columns, and a single column, :sepal-length, is a panel drawing that column. A vector in the list of cells is never a cell: it is a row of cells, or an arrangement of its own. The layers are added afterwards, once, and are drawn in every cell:

(-> (rdatasets/datasets-iris)
    (pj/arrange [{:x :sepal-length :y :sepal-width}
                 {:x :sepal-length :y :petal-length}])
    pj/lay-point)
sepal width56782.02.53.03.54.04.5petal length56781234567sepal length

A layer that names columns is drawn in the cells it fits: the cells whose columns agree with the columns the layer names, and whose number of columns the layer type can draw (Rule LP2 in Pose Rules states the rule exactly). Below, the trend line names the first cell’s columns and is drawn there only:

(-> (rdatasets/datasets-iris)
    (pj/arrange [{:x :sepal-length :y :sepal-width}
                 {:x :sepal-length :y :petal-length}])
    pj/lay-point
    (pj/lay-smooth :sepal-length :sepal-width))
sepal width56782.02.53.03.54.04.5petal length56781234567sepal length

The two cells read one dataset, so the two cells share the :x axis on which both draw :sepal-length, and that axis is titled once (see Shared Scales below). A layer that fits no cell is drawn in every cell, beside each cell’s own layers: a histogram naming :sepal-length fits neither cell, because each cell draws two columns and a histogram reads one, so it is drawn over the points in both. A layer added to the arrangement is drawn under the layers a cell holds of its own. See Rules LP2 and LP3 in Pose Rules and Panels.

A pj/lay-* call adds no cell. An arrangement is built in steps with pj/arrange: given an arrangement, pj/arrange adds the new cells after the arrangement’s own cells and draws what one pj/arrange call with the longer list draws, so a third panel joins the row:

(-> (rdatasets/datasets-iris)
    (pj/arrange [{:x :sepal-length :y :sepal-width}
                 {:x :sepal-length :y :petal-length}])
    (pj/arrange [{:x :sepal-length :y :petal-width}])
    pj/lay-point)
sepal width682.02.53.03.54.04.5petal length681234567petal width680.00.51.01.52.02.5sepal length

A cell can also hold a row filter, {:where {:species "setosa"}}, and draw the rows that match it, as Cells that filter the data shows.

pj/arrange divides space equally among its cells unless the plot options :col-weights or :row-weights give the columns and rows of cells unequal shares, as Panels of Unequal Size below shows.

Explicit Composite Poses

Under pj/arrange there is a plain-map composite pose. You can construct one directly when you want to write the tree of sub-poses as a literal map, with a weight for each sub-pose under :layout.

An explicit :layout accepts :direction (:horizontal or :vertical) and :weights (one weight per sub-pose). Here the first cell gets twice the width of the second:

(def weighted
  (pj/pose
   {:layout {:direction :horizontal :weights [2 1]}
    :poses [{:mapping {:x :sepal-length :y :sepal-width}
             :layers [{:layer-type :point}]}
            {:mapping {:x :petal-length :y :petal-width}
             :layers [{:layer-type :point}]}]
    :data (rdatasets/datasets-iris)}))

pj/pose accepts a literal composite map and tags it for notebook auto-render – the same pose value the threaded API produces:

weighted
sepal widthsepal length56782.02.53.03.54.04.5petal widthpetal length2460.00.51.01.52.02.5

And printed, showing the composite’s structure – :layout with direction and weights at the top, then each sub-pose with its own :mapping and :layers, and the outer :data dataset:

(kind/pprint weighted)
{:layout {:direction :horizontal, :weights [2 1]},
 :poses
 [{:mapping {:x :sepal-length, :y :sepal-width},
   :layers [{:layer-type :point}]}
  {:mapping {:x :petal-length, :y :petal-width},
   :layers [{:layer-type :point}]}],
 :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 |
}

The outer :data is inherited by both sub-poses. Each sub-pose has its own :mapping and :layers, and need not repeat the dataset. Subsequent examples in this chapter follow the same shape and show only the rendered plot.

Panels of Unequal Size

A histogram beside a scatter plot reads well narrower than the scatter, and a plot printed beside others may need panels of an exact size. An arrangement’s columns and rows of cells are equal by default; two pairs of plot options change that.

:col-weights and :row-weights give each column and row of panels its share of the plot, which keeps its :width and :height. The tick labels, strips and titles take their room first, and the weights share out the rest, so [2 1] draws the first panel twice as wide as the second:

(-> (rdatasets/ggplot2-mpg)
    (pj/arrange [{:x :displ :y :hwy} :hwy] {:col-weights [2 1]}))
hwydispl23456715202530354045counthwy2040010203040506070

:panel-width and :panel-height pin the panels in drawing units instead, and the plot’s size is worked out from them, as it is for a single plot. A number gives every column of panels the same width (or every row the same height), and a vector gives one value for each column (or row) in turn. Here the two columns are 300 and 150 wide, and the row is 200 high:

(-> (rdatasets/ggplot2-mpg)
    (pj/arrange [{:x :displ :y :hwy} :hwy] {:panel-width [300 150] :panel-height 200}))
hwydispl246203040counthwy20400204060

Giving both kinds for one direction, :panel-width with :col-weights, reports an error. A facet over categories draws its panels at one size, so a vector there reports an error too; a facet over columns, such as a scatter plot matrix, takes them.

Shared Scales

Two cells that draw the same column are often read against each other – a marginal above a scatter, or one measurement shown for several groups – and then the two cells need one range on that axis. Whether cells share an axis by default depends on where they read their data. Cells that read the data of the pose holding them – a composite written with :data at its root, as above, or (pj/arrange data [...]) – share each axis on which they draw the same column, as the panels of a facet do. Cells that each carry data of their own, as in (pj/arrange [pose-a pose-b]), compute their own domains (the extent of data values each axis covers). :share-scales names the axes the cells share, whichever the default was, and the cells drawing the same column on such an axis are given one domain. Below, each cell holds the rows of one species, and :x is shared:

(pj/arrange
 [(-> (rdatasets/datasets-iris)
      (tc/select-rows #(= "setosa" (:species %)))
      (pj/lay-point :sepal-length :sepal-width))
  (-> (rdatasets/datasets-iris)
      (tc/select-rows #(= "virginica" (:species %)))
      (pj/lay-point :sepal-length :sepal-width))]
 {:share-scales #{:x}})
56782.22.42.62.83.03.23.43.63.84.04.24.456782.22.42.62.83.03.23.43.63.8sepal lengthsepal width

Both cells are drawn on one :x range, and each cell keeps its own :y range, because :share-scales names :x only. Only cells drawing the same column on :x share that axis: two cells drawing different columns there each keep their own range.

A date column pools the same way – an axis holds a date as a number of milliseconds, so the union across cells is defined, and the cells are ticked over it rather than each over its own dates. See Change Over Time.

What a Shared Axis Covers

A shared axis covers what the cells sharing it draw. What a cell draws is not always what its column holds: a stack of bars reaches the total of its segments, an error bar reaches its ends, and a smoothed line can dip below or rise above the points it was fitted to. Plotje measures each cell after its statistics have run, pools the measurements of the cells sharing the axis, and pads the pooled extent once. Every sharing cell then draws the same axis, and no mark is cut off at the edge of a panel.

Two shops below sell the same drinks in two halves of a year. No value in the :sold column reaches the tallest stack, and the shared :y axis of both cells reaches past that stack:

(def north-shop
  {:drink ["tea" "tea" "coffee" "coffee"]
   :half ["first" "second" "first" "second"]
   :sold [30 45 20 25]})
(def south-shop
  {:drink ["tea" "tea" "cocoa" "cocoa"]
   :half ["first" "second" "first" "second"]
   :sold [60 70 10 15]})
(pj/arrange
 [(-> north-shop (pj/lay-bar :drink :sold {:color :half :position :stack}))
  (-> south-shop (pj/lay-bar :drink :sold {:color :half :position :stack}))]
 {:share-scales #{:y}})
teacoffee020406080100120teacocoadrinksoldhalffirstsecond

A rule or a band is covered too. A rule is drawn at a value written on its layer, which no column holds. Here one cell carries a limit beyond anything either species measures, and both cells reach it:

(def limit 8.5)
(pj/arrange
 [(-> (rdatasets/datasets-iris)
      (tc/select-rows #(= "setosa" (:species %)))
      (pj/lay-point :sepal-length :sepal-width)
      (pj/lay-rule-v {:x-intercept limit :color "firebrick"}))
  (-> (rdatasets/datasets-iris)
      (tc/select-rows #(= "virginica" (:species %)))
      (pj/lay-point :sepal-length :sepal-width))]
 {:share-scales #{:x}})
56782.22.42.62.83.03.23.43.63.84.04.24.456782.22.42.62.83.03.23.43.63.8sepal lengthsepal width

A :domain that one cell specifies for a shared axis is the domain of every cell sharing that axis, since a shared axis is one axis. Below, the second cell specifies 0 to 10 for :x, and both cells are drawn on exactly that interval:

(pj/arrange
 [(-> (rdatasets/datasets-iris)
      (tc/select-rows #(= "setosa" (:species %)))
      (pj/lay-point :sepal-length :sepal-width))
  (-> (rdatasets/datasets-iris)
      (tc/select-rows #(= "virginica" (:species %)))
      (pj/lay-point {:x {:column :sepal-length :scale {:domain [0 10]}}
                     :y :sepal-width}))]
 {:share-scales #{:x}})
02468102.22.42.62.83.03.23.43.63.84.04.24.402468102.22.42.62.83.03.23.43.63.8sepal lengthsepal width

Two cells that specify different domains for one shared axis report an error naming both domains. To specify one domain for the cells, call pj/scale on the composite: (pj/scale composite :x {:domain [0 10]}) is the domain of every cell that specifies none of its own. On a shared axis, remove the :domain from the cells first: a cell that keeps its own domain reports the same error.

Columns That Share an Axis

A set of axes shares an axis among the cells that draw the same column on it. Two cells drawing different columns keep their own ranges, which is right when the columns are in different units and wrong when they measure one quantity. Highway mileage and city mileage are both in miles per gallon, and under #{:x :y} each panel still fits its own :y. Plotje prints a warning that no two cells share :y, naming the group form used next:

(-> (rdatasets/ggplot2-mpg)
    (pj/pose {:x :displ})
    pj/lay-point
    (pj/facet {:y [:hwy :cty]})
    (pj/options {:share-scales #{:x :y}}))
hwy203040cty1.52.02.53.03.54.04.55.05.56.06.57.0102030displ

The full form of :share-scales is a map from an axis to the columns that go together on that axis. Cells whose columns go together share the axis:

  • :same-column – each column goes with itself only, which is what the set says;

  • a vector of groups of columns, such as [[:hwy :cty]] – the columns of a group go together, and a column in no group goes with itself only;

  • :all – every column goes together, so every cell shares the axis.

An axis the map leaves out is not shared. Here :x is shared as before, and the two mileage columns share :y, so a point at the same height is the same mileage in both panels:

(-> (rdatasets/ggplot2-mpg)
    (pj/pose {:x :displ})
    pj/lay-point
    (pj/facet {:y [:hwy :cty]})
    (pj/options {:share-scales {:x :same-column
                                :y [[:hwy :cty]]}}))
hwy10203040cty1.52.02.53.03.54.04.55.05.56.06.57.010203040displ

A group leaves the other columns alone. With engine displacement as a third panel, the mileage panels share a range and displacement keeps its own:

(-> (rdatasets/ggplot2-mpg)
    (pj/pose {:x :year})
    pj/lay-point
    (pj/facet {:y [:hwy :cty :displ]})
    (pj/options {:share-scales {:x :same-column
                                :y [[:hwy :cty]]}}))
hwy2040cty2040displ1999200020012002200320042005200620072008246year

The columns of a group may come from different datasets, which is how two poses that name one quantity differently are read against each other:

(pj/arrange
 [(-> {:day [1 2 3] :indoor [19.0 20.5 21.0]}
      (pj/lay-line :day :indoor))
  (-> {:day [1 2 3] :outdoor [4.0 9.5 14.0]}
      (pj/lay-line :day :outdoor))]
 {:share-scales {:y [[:indoor :outdoor]]}})
indoor123468101214161820outdoor123468101214161820day

Columns that go together have to hold one type of value: numbers with numbers, dates with dates, categories with categories. A group holding a numeric column and a categorical one reports an error:

(try
  (-> (rdatasets/ggplot2-mpg)
      (pj/pose {:x :displ})
      pj/lay-point
      (pj/facet {:y [:hwy :drv]})
      (pj/options {:share-scales {:y :all}})
      pj/plan)
  (catch clojure.lang.ExceptionInfo e (ex-message e)))
":share-scales cannot share :y between these cells: columns :hwy, :drv have no one axis to be drawn on. The cells differ in column type: categorical and numerical. Cells sharing an axis must agree on the coordinate system, the column type (numerical, categorical or temporal) and the scale type (linear or log). Leave :y out of :share-scales, or name only the columns that go together."

A Shared Categorical Axis

A categorical axis is shared as the list of every category the sharing cells hold. A bar for tea then stands at the same place in each cell, and a cell with no rows for a category leaves the place of that category empty. The north shop sells no cocoa and the south shop no coffee; with :x shared, both cells list all three drinks. Each bar here is a drink’s total for the year:

(def north-totals
  {:drink ["tea" "coffee"] :sold [75 45]})
(def south-totals
  {:drink ["tea" "cocoa"] :sold [130 25]})
(pj/arrange
 [(-> north-totals (pj/lay-bar :drink :sold))
  (-> south-totals (pj/lay-bar :drink :sold))]
 {:share-scales #{:x :y}})
teacoffeecocoa020406080100120teacoffeecocoadrinksold

The two cells above have data of their own, so the categories come in the order of the cells: the drinks of the first cell, then the drink the second cell adds. Cells that are parts of one dataset – the panels of a facet, or the cells of a pose arranged over its own data – list the categories in the order of that dataset’s rows, which is the order the same plot draws them in when it is not split.

Count and Density Axes

A histogram draws a count on :y, and no column holds that count. An axis like this is shared by what is counted. Two histograms of one column share their count axis:

(pj/arrange
 [(-> (rdatasets/datasets-iris)
      (tc/select-rows #(= "setosa" (:species %)))
      (pj/lay-histogram :sepal-length))
  (-> (rdatasets/datasets-iris)
      (pj/lay-histogram :sepal-length))]
 {:share-scales #{:y}})
4.55.05.505101520255678sepal lengthcount

Histograms of different columns keep a count axis each under a set of axes, as cells drawing different columns do. A group naming the columns shares their count axes:

(-> (rdatasets/ggplot2-mpg)
    pj/pose
    pj/lay-histogram
    (pj/facet {:x [:hwy :cty]})
    (pj/options {:share-scales {:y [[:hwy :cty]]}}))
counthwy203040010203040506070countcty102030

A count, a density and the values of a column are measured in different units, so an axis holding one is never pooled with an axis holding another. {:y :all} shares every count axis with the other count axes, every density axis with the other density axes, and the axes of columns with each other. Below, the two histograms share one count axis and the scatter keeps the axis of its :hwy column:

(pj/arrange
 [(-> (rdatasets/ggplot2-mpg) (pj/lay-histogram :hwy))
  (-> (rdatasets/ggplot2-mpg) (pj/lay-histogram :cty))
  (-> (rdatasets/ggplot2-mpg) (pj/lay-point :displ :hwy))]
 {:share-scales {:y :all}})
counthwy2040010203040506070countcty102030hwydispl24615202530354045

A histogram normalized with {:normalize :density} draws a density, and shares with a density curve of the same column. A layer type added by an extension takes part by declaring what its statistic computes; see Extensibility.

Cells Drawn Flipped

:share-scales names an axis as it is drawn: :x is the horizontal axis and :y the vertical one. Under (pj/coord :flip) the column mapped to :y runs across the page, and #{:x} shares the axis that column is drawn on. (pj/scale and :x-label name the column’s own axis, whichever way that axis is drawn.) The totals of the two shops as flipped bars, sharing the horizontal axis:

(pj/arrange
 [(-> north-totals
      (pj/lay-bar :drink :sold)
      (pj/coord :flip))
  (-> south-totals
      (pj/lay-bar :drink :sold)
      (pj/coord :flip))]
 {:share-scales #{:x}})
050100teacoffee050100teacocoasolddrink

Cells That Line Up

Each cell reserves the room its own y labels need, so a cell labelled in single digits comes out wider than a cell labelled in millions, and the axis the two share covers a different extent in each. :align-panels reserves the widest y-label pad and legend column any cell needs on all of them, so every cell gets the same drawing area:

(def readings
  {:t [1 2 3 4 5]
   :rate [1.0 2.0 3.0 2.0 4.0]
   :total [1200000.0 2400000.0 1800000.0 3100000.0 2600000.0]})
(pj/arrange
 [(-> readings (pj/lay-line :t :rate))
  (-> readings (pj/lay-line :t :total))]
 {:cols 1 :share-scales #{:x} :align-panels true})
rate1234total123451500000200000025000003000000t

Pair it with :share-scales where the cells are meant to be read against one another. pj/marginal sets both – What a marginal is made of takes one apart.

A Facet Placed as a Cell

A facet shares both axes across its panels by default. Placed as a cell of an arrangement, the facet takes the arrangement’s options wherever it writes none of its own, as any cell does – and :share-scales is one of those options. Below, the arrangement shares :x across all its cells, and the facet over :drv, which writes no :share-scales, takes {:x :all} as its own: its three panels share :x and each keeps its own :y range.

(def drv-facet
  (-> (pj/pose nil :displ :hwy)
      (pj/facet :drv)))
(-> (rdatasets/ggplot2-mpg)
    (pj/arrange [[drv-facet]
                 [{:x :displ :y :cty} {:x :displ :y :hwy}]]
                {:share-scales {:x :all}})
    pj/lay-point)
hwy246203040246152025246152025f4rcty246102030hwy246203040displ

Written on the facet, :share-scales replaces the arrangement’s value for the facet’s own panels, and they share :y again:

(-> (rdatasets/ggplot2-mpg)
    (pj/arrange [[(pj/options drv-facet {:share-scales #{:x :y}})]
                 [{:x :displ :y :cty} {:x :displ :y :hwy}]]
                {:share-scales {:x :all}})
    pj/lay-point)
hwy246203040246246f4rcty246102030hwy246203040displ

Marginal Plots

The classic “scatter with top density” – a distribution strip beside the main plot – has a function of its own. pj/marginal takes a leaf pose and puts a distribution of one of its columns in a thin panel against one edge: the :x column above the panel, the :y column to its right.

(def marginal
  (-> (rdatasets/datasets-iris)
      (pj/lay-point :sepal-length :sepal-width {:color :species})
      (pj/marginal :top)))
marginal
density0.00.20.4sepal widthspeciessetosaversicolorvirginica4.55.05.56.06.57.07.58.02.02.53.03.54.04.5sepal length

The strip shares the scatter’s x axis and keeps its own value scale. Its duplicate x ticks and axis title are dropped, since the axis below describes both panels, and the two drawing areas are aligned so a value sits at the same place in each – including here, where the scatter carries a legend and the strip does not.

The color mapping does not reach the strip. A marginal describes the pose’s :x column as a whole, so one grey curve is drawn over the three colored groups below it.

:histogram draws the distribution as bars instead of a curve, and :size sets the strip’s share of the height (0.25 by default):

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/marginal :top :histogram {:size 0.35}))
count020sepal width4.55.05.56.06.57.07.58.02.02.53.03.54.04.5sepal length

A marginal on the right

:right describes the pose’s :y column instead, in a strip beside the panel. The distribution is drawn under pj/coord :flip, so its value axis runs across the strip and its baseline stands at the left edge, against the scatter:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width {:color :species})
    (pj/marginal :right))
sepal lengthspeciessetosaversicolorvirginica56782.02.53.03.54.04.5density0.00.51.0sepal width

The strip shares the panel’s vertical axis. pj/marginal writes {:share-scales #{:y}} for a marginal on the right, and under the flip the strip’s :x column is the column drawn along that axis.

A :top marginal and a :right one line up on different edges. Two panels in a column share their left and right edges, so what has to agree is the room reserved for the y title and for the legend; two panels in a row share their top and bottom edges, so what has to agree is the room below them. :align-panels reserves whichever the layout calls for.

:bottom and :left are not drawn: a strip there would sit between the panel and the axis that describes it.

Marginals on both sides

pj/marginal adds one strip. For a marginal on each side, write the grid with pj/matrix: nil in a list of columns leaves a place with no column on that axis, so that cell draws the distribution of the other column, and the corner, nil on both axes, is left empty. The weights draw the marginals a third the size of the scatter:

(pj/matrix (rdatasets/ggplot2-mpg) [:displ nil] [nil :hwy]
           {:col-weights [3 1] :row-weights [1 3]})
count02040hwydispl23456715202530354045count050

What a marginal is made of

A :top marginal is a vertical composite with a shared x, which can also be written out. Four things make it up: the weights, the shared scale, the ticks and axis title suppressed on the strip, and :align-panels. Here are the first three:

(def marginal-by-hand
  (pj/pose
   {:share-scales #{:x}
    :layout {:direction :vertical :weights [1 3]}
    :poses [{:mapping {:x :sepal-length}
             :opts {:suppress-x-ticks true :suppress-x-label true}
             :layers [{:layer-type :density}]}
            {:mapping {:x :sepal-length :y :sepal-width :color :species}
             :layers [{:layer-type :point}]}]
    :data (rdatasets/datasets-iris)}))
marginal-by-hand
density0.00.20.4sepal widthspeciessetosaversicolorvirginica4.55.05.56.06.57.07.58.02.02.53.03.54.04.5sepal length

So the two drawing areas do not line up: the strip draws no legend, reserves no column for one, and comes out wider than the scatter below it. The density then sits at a different scale from the points it describes.

That is the fourth part, and the one pj/marginal adds: :align-panels in the composite’s own :opts. It plans every cell twice, the second time with the widest pad any of them needed as a floor, so each cell reserves what the others do – the y-label pad and the legend column for a column of cells, the room below for a row of them. pj/arrange takes :align-panels among its options, as above, and a written-out composite carries it in its own :opts. pj/options does not accept it – it is a composite’s own setting rather than a plot option:

(assoc-in marginal-by-hand [:opts :align-panels] true)
density0.00.20.4sepal widthspeciessetosaversicolorvirginica4.55.05.56.06.57.07.58.02.02.53.03.54.04.5sepal length

With the key in place the written-out form is the composite pj/marginal returns, up to the weights it computes from :size. Nothing in the shape is specific to distributions, so the same four parts serve any stack of panels read against one x axis.

A Small Dashboard

Composite poses can combine heterogeneous chart types. Here is a dashboard-style 2x2 layout: a histogram of sepal length, a boxplot of sepal width by species, a scatter of petal dimensions, and a density of petal length.

Each cell is built as its own leaf pose, then pj/arrange takes rows of cells and produces the 2x2 grid:

(def dashboard
  (pj/arrange
   [[(-> (rdatasets/datasets-iris) (pj/lay-histogram :sepal-length))
     (-> (rdatasets/datasets-iris) (pj/lay-boxplot :species :sepal-width {:color :species}))]
    [(-> (rdatasets/datasets-iris) (pj/lay-point :petal-length :petal-width {:color :species}))
     (-> (rdatasets/datasets-iris) (pj/lay-density :petal-length {:color :species}))]]))
dashboard
countsepal length567801020sepal widthspeciesspeciessetosaversicolorvirginicasetosaversicolorvirginica234petal widthpetal lengthspeciessetosaversicolorvirginica246012densitypetal lengthspeciessetosaversicolorvirginica246012

Four panels, each its own layer type. pj/arrange stacks the rows vertically; each row is laid out horizontally.

Drawing Layers with Different Data

A layer can carry its own :data, written in the layer’s mapping. This is how reference lines, predictions drawn over the data, and small datasets of labels attach to a plot. The layer reads every column from its own data: the columns it names, and the columns the pose’s mapping names.

A layer with data of its own is drawn on the pose’s panel, like any other layer of the pose. A separate panel for it comes from pj/arrange.

On the same panel

Here a base scatter gets a second set of points from another dataset, whose columns are named :prediction and :error:

(def base-data
  {:fitted   [1 2 3]
   :residual [1 2 3]})
(def other-data
  (tc/dataset {:prediction [0.5 1.5 2.5]
               :error [1.5 2.5 3.5]}))
(-> base-data
    (pj/lay-point :fitted :residual {:color "#377eb8"})
    (pj/lay-point :prediction :error {:color "#e6550d" :data other-data}))
residual, errorfitted, prediction0.51.01.52.02.53.01.01.52.02.53.03.5

One panel with six points – three from each layer. Layers paint in the order they were added – see Poses – so add the layer you want on top last.

Each axis is titled by both columns drawn on it, fitted, prediction and residual, error. Where the incoming columns are the same quantity under another name, renaming them to the pose’s columns with tc/rename-columns draws the same marks under one name per axis:

(-> base-data
    (pj/lay-point :fitted :residual {:color "#377eb8"})
    (pj/lay-point :fitted :residual
                  {:color "#e6550d"
                   :data (tc/rename-columns other-data
                                            {:prediction :fitted :error :residual})}))
residualfitted0.51.01.52.02.53.01.01.52.02.53.03.5

A panel of its own

To draw the other dataset beside the base scatter, build each as a pose and arrange them:

(pj/arrange [(pj/lay-point base-data :fitted :residual {:color "#377eb8"})
             (pj/lay-point other-data :prediction :error {:color "#e6550d"})])
residualfitted123123errorprediction121.41.61.82.02.22.42.62.83.03.23.43.6

Each panel has three points and its own axis titles: the first shows fitted against residual, the second x against y.

Panels Clip Their Own Content

Each panel confines its marks to its own rectangle. A layer whose data runs past the panel’s domain – a reference line drawn well beyond the visible range, say – is clipped at the panel edge rather than painting across its neighbours. The clip is applied per panel, so a stacked arrangement draws one clip region per panel.

(def bounded
  (-> {:day [1 2 3 4 5] :reading [10 20 15 25 18]}
      (pj/lay-point :day :reading)
      (pj/lay-line {:data {:day [1 5] :reading [-200 300]}})
      (pj/scale :y {:type :linear :domain [0 30]})))
(pj/arrange [bounded bounded] {:cols 1})
readingday123450102030readingday123450102030

Notes on the Current Implementation

A few details about how composition renders today:

  • Cells with data of their own draw their own axes, titles and ticks, unless :share-scales names an axis for them to share. In (pj/arrange [pose-a pose-b] {:share-scales #{:x}}), and in cells that read the data of the pose holding them, as in (pj/arrange data [...]), a shared axis is titled once and its ticks are labelled on the outer cells only, as the panels of a facet do. Cells drawing different columns on one shared scale – under :all, or a group such as {:y [[:hwy :cty]]} – each keep their title and its tick labels. A cell drops its own with :suppress-x-ticks and :suppress-x-label in that cell’s :opts, which is what pj/marginal writes on the strip it builds. (A scatter plot matrix names its columns with strips in place of each panel’s axis titles, and labels its :x ticks along the bottom row only. A grid of cells written by hand gets these strips where it crosses a list of :x columns with a list of :y columns, as a matrix does: each grid column draws one :x column and each row one :y column. A grid whose grid columns each draw one :x column, while its rows do not each draw one :y column, titles that :x column once below each grid column, as a shared axis is titled.)

  • Plot-area edges may not line up across composite siblings, since each leaf reserves its own padding for axes and labels – two sub-poses with different label lengths, or one drawing a legend that its neighbour does not, produce visibly different panel widths. :align-panels on pj/arrange plans the cells against a common floor for both the y-label pad and the legend column, and pj/marginal turns it on (see Cells That Line Up).

  • Each cell has its own plot options. A cell is a pose, so pj/options, pj/scale and pj/coord written on it apply to that cell: one cell can be log-scaled and its neighbour linear, and each can have its own title. Written on the composite itself, a scale, a coordinate system or an option such as :x-label applies to every cell that does not set its own. The :title, :subtitle and :caption written there are drawn once, around the whole arrangement, and not in each cell. Two layers of one pose cannot read one aesthetic through different scales, and two cells can read one aesthetic through different scales: to read an aesthetic through a second scale, put the layer in a cell of its own with pj/arrange.

  • Cells that map the same column share one scale and one legend. If every leaf maps an aesthetic to the same column (for example :color :species in all cells), each cell is given one scale for it – the categories of all the cells together, or the range of all their values – and a single legend is drawn for the composite. A category is then the same color, and a value the same shade, in every cell, even where the cells hold different data. A legend is drawn once, so its scale has to hold in every cell; cells with data of their own share an axis only where :share-scales names that axis. A cell that writes its own scale for the aesthetic keeps it, and each cell then draws its own legend. A layer that writes its color instead of mapping it, such as a black trend line in one cell, is left out of this comparison, and the cells still share one legend. When the mappings disagree – or when only some leaves carry the aesthetic, as in the dashboard above – each leaf with that aesthetic draws its own legend.

  • Rows of different poses go through pj/arrange. A row of rows is built by passing nested vectors of poses to pj/arrange (the dashboard example above shows the shape). A cell may be a composite itself, so an arranged pose can be arranged again and the cell draws its own grid. Cells of unequal size are written with :col-weights and :row-weights, or with :panel-width and :panel-height – see the section on panels of unequal size. A facet by one category is drawn in rows with :cols, as in (pj/facet pose :class {:cols 4}) – see Faceting.

Below, both cells map :color to :species, and they hold different rows: the left cell holds setosa and versicolor, the right cell versicolor and virginica. Versicolor is drawn in the same color in both, and the one legend lists all three species:

(pj/arrange
 [(-> (rdatasets/datasets-iris)
      (tc/select-rows #(not= "virginica" (:species %)))
      (pj/lay-point :sepal-length :sepal-width {:color :species}))
  (-> (rdatasets/datasets-iris)
      (tc/select-rows #(not= "setosa" (:species %)))
      (pj/lay-point :sepal-length :sepal-width {:color :species}))])
sepal widthsepal length5672.02.53.03.54.04.5sepal widthsepal length682.02.22.42.62.83.03.23.43.63.8speciessetosaversicolorvirginica

A cell that is itself a composite draws its own grid. Here the left cell holds two panels of its own and the right cell holds one, so the arranged pose draws three panels in two columns:

(pj/arrange
 [(pj/arrange
   [(-> (rdatasets/datasets-iris)
        (pj/lay-point :sepal-length :sepal-width))
    (-> (rdatasets/datasets-iris)
        (pj/lay-point :petal-length :petal-width))]
   {:cols 1})
  (-> (rdatasets/datasets-iris)
      (pj/lay-histogram :sepal-length))])
sepal widthsepal length5678234petal widthpetal length246012countsepal length56780510152025

What’s Next

  • Options and Scopes – the taxonomy of mappings, plot options, and configuration (next chapter in Foundations)

  • Faceting – panels per category or per column of one pose (covered in How-to)

  • Gallery – more composition examples alongside single-plot chart types

source: notebooks/plotje_book/composition.clj