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}))])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})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}))]])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)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))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)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:
weightedAnd 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]})):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}))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.
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)))marginalThe 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}))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))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]})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-handSo 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)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}))]]))dashboardFour 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}))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})}))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"})])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})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-scalesnames 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-ticksand:suppress-x-labelin that cell’s:opts, which is whatpj/marginalwrites 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:xticks along the bottom row only. A grid of cells written by hand gets these strips where it crosses a list of:xcolumns with a list of:ycolumns, as a matrix does: each grid column draws one:xcolumn and each row one:ycolumn. A grid whose grid columns each draw one:xcolumn, while its rows do not each draw one:ycolumn, titles that:xcolumn 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-panelsonpj/arrangeplans the cells against a common floor for both the y-label pad and the legend column, andpj/marginalturns it on (see Cells That Line Up).Each cell has its own plot options. A cell is a pose, so
pj/options,pj/scaleandpj/coordwritten 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-labelapplies to every cell that does not set its own. The:title,:subtitleand:captionwritten 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 withpj/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 :speciesin 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-scalesnames 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 topj/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-weightsand:row-weights, or with:panel-widthand: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}))])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))])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