30  API Reference

Complete reference for every public function in scicloj.plotje.api.

Each entry shows the docstring, a live example, and a test. For galleries of mark variations, see the Visualization Goals chapters (Distributions, Ranking, Change Over Time, Timelines, Relationships).

Sample Data

(def tiny {:x [1 2 3 4 5]
           :y [2 4 1 5 3]
           :group [:a :a :b :b :b]})
(def sales {:product [:widget :gadget :gizmo :doohickey]
            :revenue [120 340 210 95]})
(def measurements {:treatment ["A" "B" "C" "D"]
                   :mean [10.0 15.0 12.0 18.0]
                   :ci-lo [8.0 12.0 9.5 15.5]
                   :ci-hi [12.0 18.0 14.5 20.5]})

Construction

pj/pose is not a literal composition of the single-step transitions. Its 1-arity is pj/->pose, which lifts data to a pose and writes no mapping. The default mapping of data with one to three columns is inferred when the pose is drawn, by pj/infer-mapping, which the shortcuts (pj/draft, pj/plan, pj/membrane, pj/plot, pj/save) apply on the way in. The other arities read column arguments and merge a mapping into an existing pose. The examples below walk each shape.

pose

[]

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Construct or extend a pose.

On raw data (first argument is not itself a pose):

  • (pj/pose) – empty leaf.

  • (pj/pose data) – leaf with data and no mapping. On 1-3 column datasets the draft infers one (:x, then :y, then :color), so the pose renders without an explicit mapping call.

  • (pj/pose data {:color :species}) – leaf with aesthetic mapping.

  • (pj/pose data :x-col) – leaf with {:x :x-col}.

  • (pj/pose data :x-col {:color :c}) – :x and a mapping.

  • (pj/pose data :x-col :y-col) – leaf with :x and :y.

  • (pj/pose data :x-col :y-col {:color :c}) – :x, :y and a mapping.

  • (pj/pose data p), where p is a pose – p drawn from data, as a cell of pj/arrange is; (pj/pose nil p) is p. A pose carrying data of its own keeps it. A mapping after p merges into its mapping; columns after p, or a pose before it, report an error.

  • (pj/pose data [:a :b :c]) – several columns where one column goes are a series, drawn on one panel with a colour for each column. Pairs of columns, [[:a :b] [:c :d]], report an error: pj/arrange takes each pair as a mapping, {:x :a :y :b}.

Threaded over an existing pose (first argument is a pose):

  • (pj/pose fr) – pass-through; lifts a literal map for notebook auto-render if it is not already tagged.

  • (pj/pose fr :x-col :y-col) – merge :x and :y into the pose’s mapping (the root’s, on a composite), replacing the ones it had. Layers that name no columns of their own read the new ones. pj/pose does not add panels; for panels side by side, use pj/arrange.

  • (pj/pose fr :x-col :y-col {:color :c}) – same, with the aesthetic merged too.

  • (pj/pose fr {:color :c}) – aesthetic-only: merge into the mapping.

  • (pj/pose fr {}) is fr, and writing the same mapping twice gives the same pose.

  • (pj/pose fr {:data X :color :c}) – extend mapping AND replace the top-level data with X.

  • (pj/pose fr {:where {:drv "f"}}) – a row filter, kept on the pose: it draws only the rows whose columns hold those values. A second :where merges into the first, a column at a time. Written beside a mapping on raw data too, and as (pj/pose nil {:where ...}) it is the cell of pj/arrange written {:where ...}.

On a hand-built pose-shaped map (1-arity, input has :layers, :poses, or a map-valued :mapping): the map is validated and tagged with Kindly auto-render metadata, but its keys are not reordered and its :data is not coerced – the typed shape is preserved verbatim. A composite is supported at any depth: a sub-pose that itself has :poses nests, which is the shape pj/arrange builds and the shape it accepts among its own inputs.

Writing a mapping out in full. Any mapping value may be written as a map naming its source, and optionally which side of the scale to read it through:

  • {:column :species} – the column, even where a value of that name could be drawn.

  • {:value "blue"} – the color, even where the data carries a column called blue.

  • {:scale false} – draw the value as it stands rather than pass it through the aesthetic’s scale. On a column this is the only route to an identity scale: {:color {:column :hex :scale false}} draws the colors the column holds.

  • {:scale true} – read it as data. {:color {:value "Model A" :scale true}} draws one palette color and earns a legend entry.

The conventions decide when :scale is absent: a column passes through the scale, a written value is drawn on the appearance aesthetics and is a data value on :x and :y. See pj/layer-mapping-docs for what each aesthetic accepts, and pj/scale for choosing a scale’s type.

Create a leaf pose with data and columns:

(-> (rdatasets/datasets-iris)
    (pj/pose :sepal-length :sepal-width)
    pj/lay-point)
sepal widthsepal length4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

Map form – include aesthetics on the pose so every layer inherits them:

(-> (rdatasets/datasets-iris)
    (pj/pose :sepal-length :sepal-width {:color :species})
    pj/lay-point
    (pj/lay-smooth {:stat :linear-model}))
sepal widthsepal lengthspeciessetosaversicolorvirginica4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

A bare collection of scalars (numbers, strings, or keywords) is data too – it becomes a single column named :value. With no chart type, a single numeric column infers a histogram:

(pj/pose [1 4 1 5 6 2 3 3 3 2 4 5 1 2 3 4])
countvalue12345601234

with-data

[pose data]

Supply or replace the top-level dataset on a pose. Useful for building a template once and applying it to different datasets:

   (def template (-> (pj/pose)
                     (pj/pose :x :y {:color :group})
                     pj/lay-point
                     (pj/lay-smooth {:stat :linear-model})))

   (-> template (pj/with-data my-data))
   (-> template (pj/with-data other-data))

At attach time, every keyword column reference in the template’s mapping, layers, sub-poses, and facet options must exist in the dataset – otherwise an error is thrown naming the missing columns and listing what is available. Per-layer / per-sub-pose :data still overrides the top-level data.

Attach or replace the top-level dataset on a pose. Useful for building a dataless template and applying it to many datasets:

(def scatter-template
  (-> (pj/pose nil {:x :x :y :y :color :group})
      pj/lay-point))
(-> scatter-template
    (pj/with-data tiny))
yxgroupab1234512345

Map form – explicit keys on a pose:

(-> (rdatasets/datasets-iris)
    (pj/pose {:x :sepal-length :y :sepal-width})
    pj/lay-point)
sepal widthsepal length4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

Layer Functions

lay

[pose-or-data layer-type-key]

[pose-or-data layer-type-key mapping]

Add a root-scope layer. The layer attaches to :layers and is drawn on the single panel (leaf), or in every cell it fits (composite) – and in every cell where it fits none – as a pj/lay-* call’s layer is.

The layer type is named either by its keyword or by the entry pj/layer-type-lookup answers with; both behave the same. An entry is a map naming its :mark; any other value reports an error.

nil with a mapping is a template, as in pj/lay-*: (pj/lay nil :point {:x :a :y :b}) is a pose with that layer and no data.

The generic layer adder. pj/lay-point, pj/lay-bar and the other pj/lay-* functions are convenience wrappers around pj/lay with a registered layer-type key. Use pj/lay directly when you have a custom layer type (from pj/layer-type-lookup on a registered key, or a raw layer-type map from an extension):

(-> (rdatasets/datasets-iris)
    (pj/pose :sepal-length :sepal-width)
    (pj/lay :point))
sepal widthsepal length4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

The above delegates to :point – equivalent to pj/lay-point. The intended use of pj/lay is with a layer type that isn’t a built-in convenience: a registered custom layer type from an extension, or a raw layer-type map. See the Waterfall Extension chapter for the full pattern – registering a :waterfall layer type and calling (pj/lay pose :waterfall), or wrapping it in a lay-waterfall function of your own.

lay-point

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add a :point (scatter) layer to a pose.

With no columns, the layer reads the panel’s columns; on a composite pose it is added at the root and drawn in every cell whose columns are a number the layer type draws from, or in every cell where no cell’s columns are. With columns, the layer keeps them on its own mapping and is drawn where the pose draws those columns: on its panel, or under a facet over columns, in the panels of those columns. On a composite pose, a layer naming columns is added at the root and drawn in every cell whose panel draws no other column on an axis the layer names, and whose columns, together with the layer’s, are a number of columns the layer type draws from. Where no cell fits, the layer is drawn in every cell, as written; a lay-* call adds no cell – pj/arrange adds cells.

  • (lay-point pose) – a layer reading the panel’s columns.

  • (lay-point pose {:color :species}) – the same, with a mapping.

  • (lay-point data :x :y) – the data becomes a pose, and the layer names its columns.

  • (lay-point data :x :y {:color :c}) – the same, with a mapping.

The mapping accepts: :alpha :color :color-type :data :dx :dy :group :in :jitter :mark :offset-x :offset-y :position :shape :size :stat :tooltip :x :x-type :y :y-type.

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width {:color :species}))
sepal widthsepal lengthspeciessetosaversicolorvirginica4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

lay-line

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :line layer type – connected line through data points. Requires x (numerical) and y (numerical). Accepts :color, :alpha, :size (stroke width), :stroke-dash (:dashed/:dotted/:solid or a raw [dash gap] vector), :dx, :dy.

The mapping accepts: :alpha :color :color-type :data :dx :dy :group :in :mark :offset-x :offset-y :position :size :stat :stroke-dash :tooltip :x :x-type :y :y-type.

(def wave {:x (range 30)
           :y (map #(Math/sin (* % 0.3)) (range 30))})
(-> wave
    (pj/lay-line :x :y))
yx051015202530-1.0-0.8-0.6-0.4-0.20.00.20.40.60.81.0

lay-histogram

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :histogram layer type – bin numerical values into bars. Draws from one column: (lay-histogram pose :hwy) draws upright bars, and (lay-histogram pose {:y :hwy}) draws the same histogram on its side. Accepts :bins (count), :binwidth, :color, :normalize (:density for density-normalized heights).

The mapping accepts: :alpha :bins :binwidth :color :color-type :data :group :in :mark :normalize :offset-x :offset-y :position :stat :tooltip :x :x-type :y :y-type.

(-> (rdatasets/datasets-iris)
    (pj/lay-histogram :sepal-length))
countsepal length4.55.05.56.06.57.07.58.00510152025

Several columns in the mapping, {:x [...]}, are read as a series on one panel, a colour per column:

(pj/lay-histogram (rdatasets/datasets-iris) {:x [:sepal-length :sepal-width]})
countsepal length, sepal widthsepal lengthsepal width234567805101520253035404550

lay-bar

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add a :bar layer type.

  • One column: counts the rows of each category. Named on :y, as in (pj/lay-bar pose {:y :class}), the bars are drawn across. Two categorical columns report an error.

  • Two columns (x and y): uses the y value directly as the bar height.

The stat is inferred from whether a y column is present, and overridable: pass {:stat :count} to count even with a y column, or {:stat :identity} to require an explicit height. :color (with :position :dodge/:stack) gives grouped or stacked bars.

The categorical axis can be x (vertical bars) or y (horizontal bars): (pj/lay-bar pose :value :category) with a categorical y draws horizontal value bars, no pj/coord needed. (Stacked/filled horizontal bars are not yet supported directly – put the category on x and add (pj/coord :flip).) To read a numerical column as categories, write the type of the axis it is named on: {:x-type :categorical} for a column on :x, {:y-type :categorical} for a column on :y.

When both axes are numeric or temporal ((pj/lay-bar pose :x :y) with no categorical axis), each bar sits at its :x value with a width taken from 0.9 of the smallest gap between adjacent x values – a time-series bar chart, or a bar chart on a numeric :x. Grouped numeric bars currently overlap rather than dodge.

:bar-width sets how wide a bar is drawn, in the unit its axis offers. On a categorical axis it is the fraction of the category band the bar fills, 0.8 by default, as :box-width is for a box: {:bar-width 0.4} draws a bar half the usual thickness, which is how a second bar layer is read as drawn over the first rather than stacked on it. On a numeric or temporal axis, where there is no band, it is a width in data units.

The mapping accepts: :alpha :bar-width :color :color-type :data :group :in :mark :offset-x :offset-y :position :stat :tooltip :x :x-type :y :y-type.

(-> (rdatasets/datasets-iris)
    (pj/lay-bar :species))
countspeciessetosaversicolorvirginica05101520253035404550

Stacked bars: pass {:position :stack} to pj/lay-bar.

(-> (rdatasets/palmerpenguins-penguins)
    (pj/lay-bar :island {:position :stack :color :species}))
countislandspeciesAdelieGentooChinstrapTorgersenBiscoeDream020406080100120140160

100% stacked bars: pass {:position :fill} to pj/lay-bar.

(-> (rdatasets/palmerpenguins-penguins)
    (pj/lay-bar :island {:position :fill :color :species}))
countislandspeciesAdelieGentooChinstrapTorgersenBiscoeDream0.00.10.20.30.40.50.60.70.80.91.0

Pass a y column and pj/lay-bar uses it as the bar height instead of counting (value bars):

(-> sales
    (pj/lay-bar :product :revenue))
revenueproductwidgetgadgetgizmodoohickey050100150200250300350

The stat is inferred from whether a y column is present. Override it to count even when a y column is supplied:

(-> sales
    (pj/lay-bar :product :revenue {:stat :count}))
revenueproductwidgetgadgetgizmodoohickey01

A bar chart needs a categorical axis. To put the categories on a numeric column, declare it categorical with {:x-type :categorical} (or {:y-type :categorical}):

(-> {:hour [9 10 11] :sales [3 5 4]}
    (pj/lay-bar :hour :sales {:x-type :categorical}))
saleshour91011012345

The categorical axis can be either x or y. Put the category on y and the value on x for horizontal bars – no pj/coord needed (the orientation follows the categorical axis, the same way pj/lay-boxplot does):

(-> sales
    (pj/lay-bar :revenue :product))
productrevenue050100150200250300350widgetgadgetgizmodoohickey

Grouped horizontal bars dodge as well. Stacked or filled horizontal bars are not supported directly yet – put the category on x and add (pj/coord :flip) for those.

{:bar-width n} sets how wide a bar is drawn, in the unit its axis offers. On a categorical axis that is the fraction of the category band the bar fills, 0.8 by default, so 0.4 draws a bar half the usual thickness:

(-> sales
    (pj/lay-bar :product :revenue {:bar-width 0.4}))
revenueproductwidgetgadgetgizmodoohickey050100150200250300350

When neither axis is categorical, each bar sits at its own x value and there is no band, so the same option is a width in data units. The default there is 0.9 of the smallest gap between adjacent x values:

(-> {:x [1 2 3 4 5] :y [10 20 15 30 25]}
    (pj/lay-bar :x :y))
yx0.51.01.52.02.53.03.54.04.55.05.5051015202530

Set it there and the value is a width in the units :x is measured in. These x values sit one apart, so 0.3 leaves most of each gap empty:

(-> {:x [1 2 3 4 5] :y [10 20 15 30 25]}
    (pj/lay-bar :x :y {:bar-width 0.3}))
yx1.01.52.02.53.03.54.04.55.0051015202530

A temporal x gives a time-series bar chart, with calendar tick labels:

(-> {:month [#inst "2024-01-01" #inst "2024-02-01" #inst "2024-03-01"]
     :revenue [120 180 150]}
    (pj/lay-bar :month :revenue))
revenuemonthJan-01Jan-08Jan-15Jan-22Jan-29Feb-05Feb-12Feb-19Feb-26020406080100120140160180

lay-smooth

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :smooth layer type – a smoothed trend line. Defaults to LOESS (local regression). Pass {:stat :linear-model} for ordinary least squares instead. Requires x and y (both numerical). Accepts {:confidence-band true} for a confidence ribbon, and :stroke-dash.

The mapping accepts: :alpha :bandwidth :bootstrap-resamples :color :color-type :confidence-band :data :dx :dy :group :in :level :mark :offset-x :offset-y :position :size :stat :stroke-dash :tooltip :x :x-type :y :y-type.

Linear regression: pass {:stat :linear-model} to pj/lay-smooth.

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/lay-smooth {:stat :linear-model}))
sepal widthsepal length4.55.05.56.06.57.07.58.02.02.53.03.54.04.5
(-> (let [r (rng/rng :jdk 42)
          xs (vec (range 50))]
      {:x xs
       :y (mapv #(+ (Math/sin (* % 0.2))
                    (* 0.3 (- (rng/drandom r) 0.5)))
                xs)})
    (pj/lay-point :x :y)
    (pj/lay-smooth {:bandwidth 0.2}))
yx05101520253035404550-1.2-1.0-0.8-0.6-0.4-0.20.00.20.40.60.81.0

lay-density

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :density layer type – kernel density estimate curve. Draws from one numerical column: (lay-density pose :hwy) draws the curve upright, and (lay-density pose {:y :hwy}) draws it on its side. Accepts :color (fill), :bandwidth, and an opt-in outline on the curve: :stroke (outline color), :stroke-width, :stroke-dash (:dashed/:dotted/:solid or a raw [dash gap] vector).

The mapping accepts: :alpha :bandwidth :color :color-type :data :group :in :mark :offset-x :offset-y :position :stat :stroke :stroke-dash :stroke-width :tooltip :trim :x :x-type :y :y-type.

(-> (rdatasets/datasets-iris)
    (pj/lay-density :sepal-length))
densitysepal length4.55.05.56.06.57.07.58.00.00.050.10.150.20.250.30.350.4

lay-area

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :area layer type – filled region between y and the baseline. Requires x and y (both numerical). Accepts :color (fill), :alpha, and an opt-in outline on the top curve: :stroke (outline color), :stroke-width, :stroke-dash.

The mapping accepts: :alpha :color :color-type :data :group :in :mark :offset-x :offset-y :position :stat :stroke :stroke-dash :stroke-width :tooltip :x :x-type :y :y-type.

(-> wave
    (pj/lay-area :x :y))
yx051015202530-1.0-0.8-0.6-0.4-0.20.00.20.40.60.81.0

Stacked areas: pass {:position :stack} to pj/lay-area.

(-> {:x (concat (range 10) (range 10) (range 10))
     :y (concat [1 2 3 4 5 4 3 2 1 0]
                [2 2 2 3 3 3 2 2 2 2]
                [1 1 1 1 2 2 2 1 1 1])
     :group (concat (repeat 10 "A") (repeat 10 "B") (repeat 10 "C"))}
    (pj/lay-area :x :y {:position :stack :color :group}))
yxgroupABC02468012345678910

lay-text

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :text layer type – text labels at data coordinates. Requires x, y, and {:text :column} for label content. :align-x (:left/:center/:right, default :left) and :align-y (:top/:center/:bottom, default :center) set which part of the text lands on the data point – e.g. :align-x :right tucks the label inside a bar’s end, extending leftward. :box puts the text on a background box: true for the default box, or a map of box properties ({:corner-radius 8}). pj/lay-label is this layer with the box on.

The mapping accepts: :align-x :align-y :alpha :box :color :color-type :data :dx :dy :font-size :font-style :font-weight :group :in :mark :offset-x :offset-y :position :stat :text :tooltip :x :x-type :y :y-type.

(-> {:x [1 2 3 4] :y [4 7 5 8] :name ["A" "B" "C" "D"]}
    (pj/lay-text :x :y {:text :name}))
yxABCD123445678

lay-label

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :label layer type – text labels on a background box at data coordinates, for readability over dense data.

:label is the :text layer type with {:box true} preset, so it draws through the same mark and takes the same options, including :align-x/:align-y (defaults :left/:center); the box follows the anchored text. Pass :box to shape it – {:box {:corner-radius 0}} for square corners, {:box false} for bare text.

The mapping accepts: :align-x :align-y :alpha :box :color :color-type :data :dx :dy :font-size :font-style :font-weight :group :in :mark :offset-x :offset-y :position :stat :text :tooltip :x :x-type :y :y-type.

(-> {:x [1 2 3 4] :y [4 7 5 8] :name ["A" "B" "C" "D"]}
    (pj/lay-point :x :y {:size 5})
    (pj/lay-label {:text :name}))
yxABCD123445678

lay-boxplot

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :boxplot layer type – box-and-whisker plot. Requires categorical x and numerical y. Shows median, quartiles, whiskers, and outliers. Accepts :color for grouped boxplots.

The mapping accepts: :alpha :box-width :color :color-type :data :group :in :mark :offset-x :offset-y :position :size :stat :tooltip :x :x-type :y :y-type.

(-> (rdatasets/datasets-iris)
    (pj/lay-boxplot :species :sepal-width))
sepal widthspeciessetosaversicolorvirginica2.02.53.03.54.04.5

lay-violin

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :violin layer type – mirrored density estimate by category. Requires categorical x and numerical y. Accepts :color, :bandwidth.

The mapping accepts: :alpha :bandwidth :color :color-type :data :group :in :mark :offset-x :offset-y :position :size :stat :tooltip :trim :x :x-type :y :y-type.

(-> (rdatasets/reshape2-tips)
    (pj/lay-violin :day :total-bill))
total billdaySunSatThurFri5101520253035404550

lay-errorbar

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :errorbar layer type – vertical error bars from pre-computed bounds. Requires x, y, and {:y-min :col :y-max :col} for lower/upper bounds.

The mapping accepts: :alpha :cap-width :color :color-type :data :dx :dy :group :in :mark :offset-x :offset-y :position :size :stat :tooltip :x :x-type :y :y-max :y-min :y-type.

(-> measurements
    (pj/lay-point :treatment :mean)
    (pj/lay-errorbar {:y-min :ci-lo :y-max :ci-hi}))
meantreatmentABCD8101214161820

lay-lollipop

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :lollipop layer type – dot on a stem from the baseline. Requires categorical x and numerical y. Like a value bar but with a circle+line instead of a filled rectangle.

The mapping accepts: :alpha :color :color-type :data :group :in :mark :offset-x :offset-y :position :size :stat :tooltip :x :x-type :y :y-type.

(-> sales
    (pj/lay-lollipop :product :revenue))
revenueproductwidgetgadgetgizmodoohickey050100150200250300350

lay-tile

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :tile layer type – colored grid cells (heatmap). With :fill or :color: one cell per row, colored from a column. With neither: auto-binned 2D histogram (stat :bin2d).

A categorical :color column colors each cell from the palette, one color per category, as it colors any mark: :color-values and :color-label apply, and the fill settings, which shape a gradient, do not.

A numeric :color column is read as the fill. Its cells and their legend read the fill settings: a :fill scale spec, then a :color one, then the :fill-* plot options, then the :color-* ones – :fill-label before :color-label for the legend title.

Given both :fill and :color, the cells are painted from :fill and :color is not drawn, with a warning.

The mapping accepts: :alpha :color :color-type :data :density-2d-grid :fill :group :in :mark :offset-x :offset-y :position :stat :tooltip :x :x-type :y :y-type.

(-> (rdatasets/datasets-iris)
    (pj/lay-tile :sepal-length :sepal-width))
sepal widthsepal lengthcount024684.55.05.56.06.57.07.58.02.02.53.03.54.04.5

lay-density-2d

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :density-2d layer type – 2D kernel density heatmap. Requires x and y (both numerical). Produces a smoothed density surface as colored tiles with a continuous gradient legend.

The mapping accepts: :alpha :color :color-type :data :density-2d-grid :group :in :mark :offset-x :offset-y :position :stat :tooltip :x :x-type :y :y-type.

(-> (rdatasets/datasets-iris)
    (pj/lay-density-2d :sepal-length :sepal-width))
sepal widthsepal lengthrelative density051015202534567891.52.02.53.03.54.04.55.0

lay-contour

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :contour layer type – iso-density contour lines from 2D KDE. Requires x and y (both numerical). Accepts {:levels 10} for the number of contour levels.

The mapping accepts: :alpha :color :color-type :data :group :in :levels :mark :offset-x :offset-y :position :size :stat :tooltip :x :x-type :y :y-type.

(-> (rdatasets/datasets-iris)
    (pj/lay-contour :sepal-length :sepal-width))
sepal widthsepal lengthrelative density051015202534567891.52.02.53.03.54.04.55.0

lay-ridgeline

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :ridgeline layer type – stacked density curves by category. Requires categorical x and numerical y. Categories stack vertically with density curves rendered horizontally.

The mapping accepts: :alpha :bandwidth :color :color-type :data :group :in :mark :offset-x :offset-y :position :stat :tooltip :trim :x :x-type :y :y-type.

(-> (rdatasets/datasets-iris)
    (pj/lay-ridgeline :species :sepal-length))
speciessepal length4.55.05.56.06.57.07.58.0setosaversicolorvirginica

lay-rug

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :rug layer type – short tick marks along the axis showing individual values. Draws from one column: (lay-rug pose :hwy) marks the values along :x, and (lay-rug pose {:y :hwy}) along :y. A rug naming no column marks the panel’s :x; a written :side (:x, :y or :both) decides the axis. Often layered with density or scatter.

The mapping accepts: :alpha :color :color-type :data :group :in :length :mark :offset-x :offset-y :position :side :stat :tooltip :x :x-type :y :y-type.

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/lay-rug {:side :both}))
sepal widthsepal length4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

lay-step

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :step layer type – staircase line (horizontal then vertical). Requires x and y (both numerical). Accepts :stroke-dash.

The mapping accepts: :alpha :color :color-type :data :group :in :mark :offset-x :offset-y :position :size :stat :stroke-dash :tooltip :x :x-type :y :y-type.

(-> tiny
    (pj/lay-step :x :y)
    pj/lay-point)
yx1234512345

lay-summary

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :summary layer type – mean +/- standard error per category. Requires categorical x and numerical y. Shows a point at the mean with error bars for +/- 1 SE. Accepts :color for grouped summaries.

The mapping accepts: :alpha :color :color-type :data :group :in :mark :offset-x :offset-y :position :size :stat :tooltip :x :x-type :y :y-type.

(-> (rdatasets/datasets-iris)
    (pj/lay-summary :species :sepal-length))
sepal lengthspeciessetosaversicolorvirginica5.05.25.45.65.86.06.26.46.6

lay-interval-h

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :interval-h layer type – horizontal bar from x to x-end at categorical y. Each row becomes one rectangle; the y column is treated categorically so each distinct value occupies its own lane. Required: x (numeric or temporal start), y (categorical lane), :x-end column ref in opts (numeric or temporal end). Accepts :color, :alpha, :interval-thickness (band fill fraction, 0.0-1.0, default 0.7). (lay-interval-h data :start :task {:x-end :end :color :status})

The mapping accepts: :alpha :color :color-type :data :group :in :interval-thickness :mark :offset-x :offset-y :stat :tooltip :x :x-end :x-type :y :y-type.

(-> {:start [#inst "2024-01-01" #inst "2024-03-01" #inst "2024-05-01"]
     :end   [#inst "2024-04-01" #inst "2024-06-01" #inst "2024-08-01"]
     :task  ["Design" "Build" "Test"]}
    (pj/lay-interval-h :start :task {:x-end :end}))
taskstartJanFebMarAprMayJunJulAugDesignBuildTest

lay-segment

[pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :segment layer type – a straight line from (x, y) to (x-end, y-end), one per row.

:x-end and :y-end each take a column or a written value, and an end left out is the start’s own value. So {:y-end 0} draws a stem from each point down to the zero line – a stem plot, a lollipop without its dot – and {:x-end :x1 :y-end :y1} draws each row’s segment between two points. :arrow puts an arrow head on :end, :start or :both ends. A bare name is read as a column, as it is on :x, so a category is written as a value: {:x-end {:value "Q4"}}.

  • (lay-segment data :index :distance {:y-end 0}) – stems.
  • (lay-segment data :x0 :y0 {:x-end :x1 :y-end :y1 :arrow :end})
  • (lay-segment data :quarter :sales {:x-end {:value "Q4"}}) – each row’s segment runs to the Q4 category.

The mapping accepts: :alpha :arrow :color :color-type :data :dx :dy :group :in :mark :offset-x :offset-y :size :stat :stroke-dash :tooltip :x :x-end :x-type :y :y-end :y-type.

(-> {:x0 [1 2 4] :y0 [1 3 2] :x1 [3 3 5] :y1 [2 1 4]}
    (pj/lay-segment :x0 :y0 {:x-end :x1 :y-end :y1 :arrow :end}))
y0x0123451234

Reference Lines and Bands

Reference lines and shaded bands are regular layers. Where each one draws comes from its mapping (:y-intercept for lay-rule-h, :x-intercept for lay-rule-v; :y-min/:y-max for lay-band-h, :x-min/:x-max for lay-band-v); :color overrides the default reference color, :alpha the opacity – which on a band overrides the :band-opacity configuration default – and :size a rule’s width. On a composite, a rule or a band written without columns is added at the root and drawn in every cell with two columns – in every cell, where no cell has two columns. One written with an :x and a :y column is placed as any pj/lay-* naming columns is (Pose Rules, Rules LP2 and LP3). On a pose with one panel a rule or a band is drawn on that panel, and columns written on it that the panel does not draw are not read, with a warning.

They are drawn in the order they were added, like any other layer, so a rule written before a scatter sits under its points. The axis the value is written on reaches that value, so a rule written outside everything the data covers widens that axis rather than disappearing; a :domain written with pj/scale replaces what the data covers and pins the axis where the rule cannot widen it.

The other axis – the one the rule reaches across, or the one a band spans – takes no extent from the rule or the band. A rule names a value on one axis only, and the axis it crosses keeps the extent the other layers give it, so a rule drawn over a density leaves the curve at the height the density computed. Where nothing else gives that axis an extent it runs from 0 to 1.

On a categorical axis a number written here is a place among the categories, counted from one, as a number written for :x or :y is: (pj/lay-rule-v {:x-intercept 2}) draws down the middle of the second band. Such an axis cannot widen to reach a value, so a place past its ends reports an error rather than being drawn off the panel. Placing Marks teaches the reading.

Rule intercepts also accept temporal values (LocalDate, LocalDateTime, Instant, java.util.Date) so a date-axis intercept needs no manual conversion – see the second lay-rule-v example below.

Note on :y-min/:y-max. The same option keys carry two meanings depending on the layer type. On lay-band-h/-v they are written numeric bounds (the band sits at fixed coordinates, independent of the data). On lay-errorbar (above) they are column references – one row per error bar, with :y-min and :y-max naming columns that supply the lower and upper bounds. ggplot2 keeps these separate via aes() (column) versus a value written outside it; Plotje overloads the keyword and dispatches by mark. Writing the mapping in full – {:column :lo} on the errorbar, {:value 12} on the band – says which reading you mean without changing which one the mark accepts.

Writing a band’s number on an errorbar reports an error. The message names the mark, the key, the value, the columns the layer’s data holds, and the mark that reads these two keys as numbers:

(try (-> measurements
         (pj/lay-point :treatment :mean)
         (pj/lay-errorbar {:y-min 0.5 :y-max 1.5})
         pj/plan)
     (catch Exception e (ex-message e)))
"pj/lay-errorbar :y-min 0.5 is not a column of this layer's data. lay-errorbar reads :y-min as a column, one bound per row: (pj/lay-errorbar data :x-column :y-column {:y-min :lo-column :y-max :hi-column}). Available columns: [:ci-hi :ci-lo :mean :treatment]. On pj/lay-band-h these two keys take a written number instead, and shade one region between them."

An errorbar given one bound without the other reports an error too, and the message names the bound that was given. An errorbar reads both bounds, one bound per row:

(try (-> measurements
         (pj/lay-point :treatment :mean)
         (pj/lay-errorbar {:y-min :ci-lo})
         pj/plan)
     (catch Exception e (ex-message e)))
"errorbar/pointrange requires :y-min and :y-max columns, and got :y-min alone. Name both in the layer's mapping: (pj/lay-errorbar data :treatment :mean {:y-min :lo-column :y-max :hi-column})."

lay-rule-v

[_pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :rule-v layer – vertical reference line at x = x-intercept. The value is written in the mapping rather than read from a column; :x-intercept is required. Accepts :x-intercept (numeric or temporal – LocalDate, LocalDateTime, Instant, java.util.Date), :color (a written color), :alpha (the line’s opacity), :size (its width) and :stroke-dash (:dashed/:dotted/:solid or a raw [dash gap] vector). Temporal values are converted internally to match the x-axis scale so a date-axis intercept needs no manual conversion. {:in :drawing-area} reads the intercept as drawing units from the top left of the panel background instead of as a data value. The rule is drawn in the order its layer was written, so one written before a scatter sits under its points and one written after sits over them. Written with no columns, the rule is drawn on the pose’s panel, and on a composite pose in every cell whose panel draws two columns, or in every cell where no cell’s panel does. On a composite pose the 4-arity draws the rule in every cell whose panel draws no column other than the two it names, and in every cell where no cell’s panel does. On a pose with one panel, a column the panel does not draw is not read, and a warning names it; the rule is still drawn on that panel.

  • (lay-rule-v pose {:x-intercept 5}) – no columns: on every panel of a leaf; on a composite, as above.

  • (lay-rule-v pose :height :weight {:x-intercept 5}) – on a composite pose, in every cell whose panel draws no column other than :height and :weight.

  • (lay-rule-v pose {:x-intercept 5 :color "red"}) – with override color.

  • (lay-rule-v pose {:x-intercept #inst "2008-09-15"}) – temporal intercept on a date axis.

The mapping accepts: :alpha :color :data :in :mark :offset-x :offset-y :size :stat :stroke-dash :tooltip :x :x-intercept :y.

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/lay-rule-v {:x-intercept 6.0}))
sepal widthsepal length4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

A temporal rule on a date axis – the same pose pattern, with :x-intercept taking a LocalDate.

(-> {:date  [#inst "2024-01-01" #inst "2024-04-01" #inst "2024-08-01"]
     :value [3 5 9]}
    (pj/lay-line :date :value)
    (pj/lay-rule-v {:x-intercept (java.time.LocalDate/parse "2024-06-01")
                    :color "#c0392b"}))
valuedateJanFebMarAprMayJunJulAug3456789

lay-rule-h

[_pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :rule-h layer – horizontal reference line at y = y-intercept. The value is written in the mapping rather than read from a column; :y-intercept is required. Accepts :y-intercept (numeric or temporal – LocalDate, LocalDateTime, Instant, java.util.Date), :color (a written color), :alpha (the line’s opacity), :size (its width) and :stroke-dash (:dashed/:dotted/:solid or a raw [dash gap] vector). Temporal values are converted internally to match the y-axis scale so a date-axis intercept needs no manual conversion. {:in :drawing-area} reads the intercept as drawing units from the top left of the panel background instead of as a data value. The rule is drawn in the order its layer was written, so one written before a scatter sits under its points and one written after sits over them. Written with no columns, the rule is drawn on the pose’s panel, and on a composite pose in every cell whose panel draws two columns, or in every cell where no cell’s panel does. On a composite pose the 4-arity draws the rule in every cell whose panel draws no column other than the two it names, and in every cell where no cell’s panel does. On a pose with one panel, a column the panel does not draw is not read, and a warning names it; the rule is still drawn on that panel.

  • (lay-rule-h pose {:y-intercept 3}) – no columns: on every panel of a leaf; on a composite, as above.

  • (lay-rule-h pose :height :weight {:y-intercept 3}) – on a composite pose, in every cell whose panel draws no column other than :height and :weight.

  • (lay-rule-h pose {:y-intercept 3 :color "red"}) – with override color.

  • (lay-rule-h pose {:y-intercept (java.time.LocalDate/parse "2024-01-01")}) – temporal intercept on a date axis.

The mapping accepts: :alpha :color :data :in :mark :offset-x :offset-y :size :stat :stroke-dash :tooltip :x :y :y-intercept.

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/lay-rule-h {:y-intercept 3.0}))
sepal widthsepal length4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

lay-band-v

[_pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :band-v layer – vertical shaded band between x = x-min and x = x-max. The bounds are written in the mapping rather than read from a column; :x-min and :x-max are required and :x-min must be <= :x-max. Accepts :x-min (required), :x-max (required), :color (a written color) and :alpha. Bounds may be numeric or temporal (LocalDate, LocalDateTime, Instant, java.util.Date); temporal values are converted internally to match the x-axis scale. {:in :drawing-area} reads the bounds as drawing units from the top left of the panel background instead of as data values. The band is drawn in the order its layer was written, so one written before a scatter sits under its points. Written with no columns, the band is drawn on the pose’s panel, and on a composite pose in every cell whose panel draws two columns, or in every cell where no cell’s panel does. On a composite pose the 4-arity draws the band in every cell whose panel draws no column other than the two it names, and in every cell where no cell’s panel does. On a pose with one panel, a column the panel does not draw is not read, and a warning names it; the band is still drawn on that panel.

  • (lay-band-v pose {:x-min 4 :x-max 6}) – no columns: on every panel of a leaf; on a composite, as above.

  • (lay-band-v pose :height :weight {:x-min 4 :x-max 6}) – on a composite pose, in every cell whose panel draws no column other than :height and :weight.

  • (lay-band-v pose {:x-min 4 :x-max 6 :color "blue" :alpha 0.3}) – with color and opacity overrides.

The mapping accepts: :alpha :color :data :in :mark :offset-x :offset-y :stat :tooltip :x :x-max :x-min :y.

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/lay-band-v {:x-min 5.5 :x-max 6.5}))
sepal widthsepal length4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

lay-band-h

[_pose-or-data]

[pose-or-data x-or-mapping]

[pose-or-data x y-or-mapping]

[pose-or-data x y mapping]

Add :band-h layer – horizontal shaded band between y = y-min and y = y-max. The bounds are written in the mapping rather than read from a column; :y-min and :y-max are required and :y-min must be <= :y-max. Accepts :y-min (required), :y-max (required), :color (a written color) and :alpha. Bounds may be numeric or temporal (LocalDate, LocalDateTime, Instant, java.util.Date); temporal values are converted internally to match the y-axis scale. {:in :drawing-area} reads the bounds as drawing units from the top left of the panel background instead of as data values. The band is drawn in the order its layer was written, so one written before a scatter sits under its points. Written with no columns, the band is drawn on the pose’s panel, and on a composite pose in every cell whose panel draws two columns, or in every cell where no cell’s panel does. On a composite pose the 4-arity draws the band in every cell whose panel draws no column other than the two it names, and in every cell where no cell’s panel does. On a pose with one panel, a column the panel does not draw is not read, and a warning names it; the band is still drawn on that panel.

  • (lay-band-h pose {:y-min 2 :y-max 4}) – no columns: on every panel of a leaf; on a composite, as above.

  • (lay-band-h pose :height :weight {:y-min 2 :y-max 4}) – on a composite pose, in every cell whose panel draws no column other than :height and :weight.

  • (lay-band-h pose {:y-min 2 :y-max 4 :color "blue" :alpha 0.3}) – with color and opacity overrides.

The mapping accepts: :alpha :color :data :in :mark :offset-x :offset-y :stat :tooltip :x :y :y-max :y-min.

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/lay-band-h {:y-min 2.5 :y-max 3.5}))
sepal widthsepal length4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

Transforms

coord

[pose coord-type]

Set coordinate transform on a pose. The coord applies to the pose it is called on and to everything below it, as a scale does: called on the pose you are building it covers every panel, and called on one cell before the cells are arranged, that cell alone. On a composite pose it attaches to the root, so every descendant leaf inherits it at plan time.

Supported coord-types:

  • :cartesian – standard x-right, y-up mapping (the default).
  • :flip – swap x and y axes (horizontal bars / boxplots).
  • :fixed – equal aspect ratio (1 data unit = 1 data unit).
  • :polar – radial mapping: x to angle, y to radius.

A pose that names a column on :y alone, under layers that draw from one column, is drawn on its side, and takes :flip or no coordinate system: :cartesian, :polar and :fixed report an error.

Flip axes:

(-> (rdatasets/datasets-iris)
    (pj/lay-bar :species)
    (pj/coord :flip))
speciescount05101520253035404550setosaversicolorvirginica

Polar coordinates:

(-> (rdatasets/datasets-iris)
    (pj/lay-bar :species)
    (pj/coord :polar))
countspeciessetosaversicolorvirginica02040

scale

[pose aesthetic scale-type]

Set scale on a pose. The scale applies to the pose it is called on and to everything below it: called on the pose you are building, it covers the whole plot; called on one cell before the cells are arranged, that cell alone, so two cells can carry different scales. Under faceting every panel comes from one pose, so the panels share a type; {:share-scales #{}} varies their domains.

A mapping written out in full can name a scale too, for that one mapping: {:size {:column :weight :scale :log}}. Where a scale is set at more than one scope the settings accumulate and the inner scope wins, key by key. Written on the same pose, this call is the inner one; written on a layer, the layer’s mapping is.

Accepts a type keyword or a scale spec map. :type and :domain belong to every scale. The rest are per aesthetic, and a key an aesthetic does not read reports an error:

  • Every aesthetic takes :label, the title of whatever explains its scale to a reader: the axis for :x and :y, the legend for the rest. It wins over the <aesthetic>-label plot option – :x-label, :color-label and their siblings – which names the same thing one scope further out.

  • :x and :y take :include, a value the axis has to reach, or a collection of them. {:include 0} puts zero on the axis so that lengths drawn along it are proportional to the values, and the value lands exactly at the edge of the panel. :include extends the extent the data gives where :domain replaces it, so the two are not written together, and it is a set of values where a :domain is an ordered pair.

  • :x and :y take :breaks (explicit tick locations; [] draws the axis with no ticks, tick labels or grid lines, as ggplot2’s breaks = NULL does, while nil leaves the default ticks), :tick-labels (custom tick text paired with :breaks), :n-ticks (about this many ticks) and :tick-spacing (about this much room in drawing units per tick). A numeric axis reads whichever of the last two is named; a categorical one is ticked at its categories, which :n-ticks thins.

  • :size and :alpha take :range – what the aesthetic spans, in the quantity the mark draws it as, so [2 8] on :size is a radius in drawing units.

  • :size further takes :by, how a value spreads across that range (:sqrt by default, or :linear or :area), and :from-zero, which anchors both the domain and the range at zero so that twice the value is twice the ink.

  • :shape takes :values, the marker symbols to draw with.

  • :color and :fill take :range, the gradient a numeric column is read through; :color also takes :values, the colours a categorical column is drawn in. Both take :midpoint, the value the middle of the gradient is drawn at.

A value outside :domain is drawn at the nearer end rather than dropped, so a narrower domain says what the reader should compare without leaving rows off the panel. On an axis a :domain is two finite numbers, or two dates where the column is temporal; against a categorical column it is the list of categories, in the order they are to be drawn.

Aesthetics and accepted scale types:

  • The axis aesthetics (:x, :y) accept :linear, :log, :categorical.

  • The continuous appearance aesthetics (:size, :alpha, :fill, :color) accept :linear and :log only – :categorical does not apply.

  • The discrete appearance aesthetic :shape accepts :categorical only – :linear and :log do not apply to a discrete encoding.

:group reports an error: it draws nothing of its own, so there is no scale to set. It splits a layer into one drawn group per value, and the order of those groups is the order of the data.

To take an aesthetic off its scale for one mapping rather than choose a type for the whole plot, write that mapping out in full: {:color {:column :hex :scale false}} draws the column’s values as they stand, and {:size {:value 7 :scale true}} sends a written value through the scale. See pj/layer-mapping-docs for :color and :size.

A :domain has two readings, and the domain itself decides which: two numbers are a range, and anything else is a list of categories.

On a categorical :color or :shape column it gives the order the categories are placed in, which the legend and the palette both follow. A category the list leaves out is still drawn, ordered after the ones listed, with a warning. On :shape, :values supplies the symbols to draw those categories with in that same order; pj/shape-symbols lists the ones available.

On :col and :row a :domain gives the order the panels of a facet are drawn in, by the same rule: the listed categories first, and a category the list leaves out after them, with a warning. It is the one scale setting a panel aesthetic takes, and it orders the panels of one column, not of a compound key.

On a numeric :color or :fill column it gives the two ends of the gradient, as it gives the ends of the drawn range on :size and :alpha. That is how every panel of a facet can be given one scale to share.

:tick-labels requires :breaks and must match it in count. Use it to draw numeric breaks with text of your own – for example, days of the week on a tile heatmap.

:n-ticks asks for about that many ticks. On a categorical axis it thins a crowded one, which otherwise labels every category; on a numeric axis it replaces the count that :tick-spacing would give. :tick-spacing asks for about that much room, in drawing units, per tick, and the count follows from how many fit. It is a target in the way :n-ticks is: the ticks are still rounded to values a reader can read off, so the room each one ends up with can come out under the number asked for. It steers the choice of numeric ticks and does nothing on a categorical axis, which says so. The :x-tick-spacing / :y-tick-spacing plot options name the same setting one scope further out.

  • (scale pose :x :log) – log scale on x-axis.

  • (scale pose :x {:type :categorical :domain [...]}) – explicit category order.

  • (scale pose :x {:n-ticks 8}) – about eight ticks, which on a crowded categorical axis thins it to eight of its categories.

  • (scale pose :y {:type :linear :breaks [0 5 10]}) – pin tick locations.

  • (scale pose :x {:type :linear :breaks [1 2 3 4 5 6 7] :tick-labels ["Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun"]}) – numeric breaks with custom tick text.

  • (scale pose :y {:type :log :domain [1 1000]}) – log scale with explicit range.

  • (scale pose :size :log) – log-spaced point sizes.

  • (scale pose :size {:range [3 14]}) – wider points than the default 2 to 8.

  • (scale pose :size {:by :area :from-zero true}) – a point of twice the value covers twice the ink.

  • (scale pose :fill :log) – log-spaced tile fill.

  • (scale pose :shape {:type :categorical :domain [...]}) – shape legend order.

  • (scale pose :shape {:values [:cross :plus]}) – pick the symbols.

  • (scale pose :col {:domain [4 5 6 8]}) – the order of a facet’s panels.

Log scale:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/scale :x :log))
sepal widthsepal length4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

Fixed domain:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/scale :x {:domain [3 9]}))
sepal widthsepal length34567892.02.53.03.54.04.5

Log scale on an appearance aesthetic (:size, :alpha, :fill, or :color):

(-> {:user [:a :b :c] :n [10 100 1000]}
    (pj/lay-point :user :n {:size :n :x-type :categorical})
    (pj/scale :size :log))
nusern101001000abc01002003004005006007008009001000

What a size spans, and how the values spread across it – :range the radii the marks run between, :by the method, and :from-zero to make the ink proportional to the value:

(-> {:user [:a :b :c] :n [10 100 1000]}
    (pj/lay-point :user :n {:size :n :x-type :categorical})
    (pj/scale :size {:range [3 16] :by :area :from-zero true}))
nusern2004006008001000abc01002003004005006007008009001000

Shape symbols on a discrete aesthetic – :domain orders the categories, :values picks the markers:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width {:shape :species})
    (pj/scale :shape {:domain ["virginica" "versicolor" "setosa"]
                      :values [:cross :plus :diamond]}))
sepal widthsepal lengthspeciesvirginicaversicolorsetosa4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

shape-symbols

[]

Every marker symbol a :shape mapping can draw.

(pj/shape-palette) is the first part, in the order categories are assigned. The rest are drawn only when named – :circle-open is a ring rather than a disc, which keeps overlapping points countable.

Pass a selection of these as :values to (pj/scale pose :shape {:values [...]}) to choose them yourself, or name one for a whole layer with {:shape :circle-open}.

A function rather than a value, as pj/config is: the list grows from one release to the next, and a value read at load time could not follow it. Adding a symbol of your own is not supported – the shapes are drawn by a fixed table in the renderer.

(pj/shape-symbols)
[:circle
 :square
 :triangle
 :diamond
 :triangle-down
 :plus
 :cross
 :circle-open]

Custom tick labels on a numeric axis – pair :breaks with :tick-labels:

(-> (for [d (range 1 8)] {:day d :v (mod d 3)})
    (pj/lay-point :day :v)
    (pj/scale :x {:type :linear
                  :breaks [1 2 3 4 5 6 7]
                  :tick-labels ["Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun"]}))
vdayMonTueWedThuFriSatSun012

Faceting

facet

[pose col]

[pose col options]

Facet a pose by a column: one panel per value the column holds, placed across. (pj/facet my-pose {:row :species}) places them down.

Faceting is a mapping. (pj/facet my-pose :species) writes {:col :species} into the pose’s mapping, so it follows the same scope rules as :color or :size – written on a pose it reaches every layer and every sub-pose below, and a sub-pose that writes its own :col overrides it. This is what lets a composite be faceted, and lets one cell of a composite be faceted differently from another.

:col and :row are aesthetics, so the mapping may be written out in full, and several columns under either unite into one compound key, as they do under :group – pj/compound-key-aesthetics lists the three:

  • (pj/facet my-pose :species) – one panel per species.

  • (pj/facet my-pose [:part :dimension]) – one panel per observed combination, which is a compound key. {:col :part :row :dimension} fills the rectangle instead.

  • {:col {:column :species}} – the same as the first, written out.

The panels are drawn in the order the data holds the column’s values. A :domain specifies another order, as it does for a categorical axis and a legend: (pj/scale my-pose :col {:domain [...]}), or beside the column, (pj/facet my-pose {:column :species :scale {:domain [...]}}).

A map without :column says where panels come from, and may name columns rather than categories. A map of columns under :x and :y draws a panel per column, and with both, pairs the columns one by one:

  • (pj/facet my-pose {:y [:hwy :cty]}) – a panel per column.
  • (pj/facet my-pose {:x [:a :b] :y [:c :d]}) – two panels, :a against :c and :b against :d.

Under :col and :row the map draws a grid: each entry is a column of categories or a map of columns, and the grid has a panel for every pair of an entry’s value across and an entry’s value down, whether the data holds the pair or not:

  • (pj/facet my-pose {:col :year :row :drv}) – categories by categories.

  • (pj/facet my-pose {:col :species :row {:y [:a :b]}}) – categories across, columns down.

  • (pj/facet my-pose {:col {:x cols} :row {:y cols}}) – a scatter plot matrix: every column of cols against every column of cols, the panel of a column against itself drawing that one column (a histogram, or a bar chart of counts for a categorical column). {:col {:x xs} :row {:y ys}} crosses two lists, and nil in a vector of columns leaves that place for a marginal distribution. (pj/matrix my-pose cols) and (pj/matrix my-pose xs ys) write these facets.

Categories are written into the pose’s mapping and columns under its :facet, and the two are crossed when the pose is drawn. So a grid may also be written as two calls, in either order – (pj/facet my-pose {:y [:a :b]}) and then (pj/facet :species) – and a facet over categories written on an arrangement crosses a cell’s facet over columns. A third distinction, where both directions are taken, reports an error.

The columns are checked against the data when pj/facet is called. A layer added to a facet over columns is placed among its panels as on a composite pose (Rules LP2 and LP3 in Pose Rules): a layer naming one of the facet’s columns is drawn in the panels of that column where the panel’s other column agrees with the layer’s, and a layer that fits no panel is drawn in every panel. A second map of columns crosses the first where it names the other direction – {:x xs} and then {:row {:y ys}} is {:col {:x xs} :row {:y ys}}; any other second map of columns, or one on a composite pose, reports an error.

nil in place of the column cancels the facet a pose above writes: (pj/facet cell nil) on one cell of a faceted arrangement draws that cell as one panel.

A map of plot options may come last, and is what pj/options takes: (pj/facet my-pose :species {:share-scales #{:x}}) is (-> my-pose (pj/facet :species) (pj/options {:share-scales #{:x}})). The map may also hold :cols, the number of panels across, for a facet by one category across: (pj/facet my-pose :class {:cols 4}) draws the panels in rows of four, each under its strip, as pj/arrange draws the cells of that facet given the same :cols.

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

:cols in the options map wraps a facet by one category into rows of that many panels:

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

A map under :col and :row draws a grid of categories, a panel for every pair of values:

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

pj/matrix writes the grid that crosses columns with columns:

matrix

[data-or-pose cols]

[data-or-pose cols options]

[data-or-pose xs ys]

[data-or-pose xs ys options]

A grid of panels crossing columns with columns: every column of xs across against every column of ys down. It is the facet {:col {:x xs} :row {:y ys}}, and returns the pose pj/facet returns for it:

(pj/matrix data xs ys options) is (pj/facet data {:col {:x xs} :row {:y ys}} options).

  • (pj/matrix data cols) – a scatter plot matrix, the columns crossed with themselves. The panel of a column against itself draws that one column: a histogram, or the counts of a categorical column.

  • (pj/matrix data xs ys) – xs across, ys down.

  • (pj/matrix data [:a nil] [nil :b]) – nil leaves a place with no column on that axis, so the cell draws the distribution of the other: a scatter plot of :a and :b with a marginal distribution of each. The corner, nil on both axes, is left empty. {:col-weights [3 1] :row-weights [1 3]} draws the marginals smaller.

The first argument is data or a pose; a mapping such as {:color :species} is written with pj/pose, before or after. A map of plot options may come last, as pj/facet takes it. Layers added afterwards are drawn as in any facet over columns: a layer reading one column on the diagonal, a layer reading two off it.

(pj/matrix (rdatasets/datasets-iris) [:sepal-length :sepal-width :petal-length])
6823468246234246sepal lengthsepal widthpetal lengthsepal lengthsepal widthpetal length

Composition

arrange

[plots]

[plots-or-data opts-or-cells]

[data-or-pose cells opts]

Arrange multiple poses in a grid. Returns a composite pose that renders through the compositor via membrane – so :svg, :bufimg, and any other membrane target work uniformly.

Each cell is a pose, leaf or composite, or – drawn from data given first, below – a column or a mapping. A composite cell holds its own grid. nil is a cell left empty: it keeps its place in the layout and draws nothing, whatever data and layers the composite carries. Pre-rendered hiccup is not accepted; build your own [:div ...] if you need to combine already-rendered values outside the library.

The options map holds the options below and any plot option pj/options takes: (arrange cells {:x-label "X"}) is (-> (arrange cells) (pj/options {:x-label "X"})), and the option reaches every cell that does not set it. A key that is neither is reported, as pj/options reports one.

  • :cols – explicit column count (default: min(4, n-plots)).

  • :title – centered title band above the grid.

  • :subtitle – a line under the title; :caption – a line under the grid, at the right.

  • :width – total composite width.

  • :height – total composite height.

  • :share-scales – the axes the cells share. A set of axes, #{:x :y}, shares each among the cells drawing the same column on it; :x is the horizontal axis and :y the vertical one, also for a cell drawn with :coord :flip. A map says which columns go together on an axis: {:y [[:hwy :cty]]} shares :y between the cells drawing :hwy and :cty, {:y :all} between every cell, and {:y :same-column} is what the set says. A shared axis covers what the cells sharing it draw; a categorical one lists every category they hold. A count or density axis is shared among cells that count the same column, and a group or :all shares it between columns. By default, cells that split the data of the pose they are arranged into share each axis that draws one column, and other cells share nothing. pj/options takes the same option for the panels of a facet.

  • :align-panels – give every cell the same drawing area, by reserving the widest y-label pad and legend column a cell needs on all of them (and, for a row, the tallest x-label pad). Two cells whose y axes label at different widths otherwise get different panel widths, so a shared x axis covers a different extent in each. Pair it with :share-scales where the cells are meant to be read against one another.

  • (arrange [fr-a fr-b] {:cols 1 :share-scales #{:x} :align-panels true}) – a column of cells whose x axes line up.

  • (arrange [fr-a fr-b]) – 1x2 row.

  • (arrange [fr-a fr-b fr-c] {:cols 2 :width 900}) – 2x2 grid (wraps).

  • (arrange [[fr-a fr-b] [fr-c fr-d]]) – explicit 2x2 grid.

Given data first, the cells are drawn from it, so a cell need say no more than which columns its panel draws and the layers are added once at the root:

  • (-> data (arrange [{:x :a :y :b} {:x :c :y :d}]) (lay-point))
  • (-> data (arrange cells {:cols 2}) (lay-point))
  • (-> data (pose {:x :a :y :b}) (arrange [{:where {:g "u"}} {:where {:g "v"}}]) (lay-point)) – a cell holding :where draws the rows that match, alone or beside a mapping. Cells that split the data by one column’s values, in the data’s order, draw what pj/facet given the same :cols draws. Without :cols an arrangement wraps its cells in rows of four, and a facet draws one row.

The arity is decided by the second argument: a sequential one is the cell list, so the first is data or a pose; a map is the options, so the first is the cells.

A cell is what one argument after the data is to pj/pose: a column, :a, is the cell {:x :a}; a mapping is a mapping; a pose is a pose. So a cell and (pj/pose nil cell) draw the same. nil is the exception: here a cell left empty, where after the data in pj/pose it names no column. A vector is never a cell. It is a list of cells – a row, in a list of rows, and otherwise an arrangement of its own. A list is a list of rows when its first element is a vector, and then every element is a row:

  • (arrange data [:a :b :c]) – a panel per column.

  • (arrange data [{:x :a :y :b} {:x :c :y :d}]) – a panel per pair of columns.

  • (arrange data [[:a :b] [:c :d]]) – a 2x2 grid of panels, a column each.

  • (arrange data [:a [:b :c]]) – a panel of :a beside an arrangement of :b and :c.

  • (arrange pose [:a :b]) – the pose’s data, mapping, layers, row filter and plot options, with a panel per column; on a composite pose, the cells appended, laid out as one call with the longer list lays them out.

  • (arrange data [(pj/pose nil :a :b) (pj/pose nil :c :d)]) – a pose with no data is drawn from the data given first, so a list of pairs is (mapv #(apply pj/pose nil %) pairs).

  • (arrange data [(pj/lay-point nil :a :b) {:x :c :y :d}]) – a cell with a layer of its own, beside a cell left to the layers of the arrangement.

(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 2 :height 250})
sepal widthsepal length682.02.53.03.54.04.5petal widthpetal length2460.00.51.01.52.02.5speciessetosaversicolorvirginica

Mappings as cells – given the data first, a mapping such as {:x :sepal-length :y :sepal-width} is a panel of its two columns. A layer added afterwards naming no columns is drawn in every cell with as many columns as its layer type draws. A layer naming columns is drawn in every cell it fits – here the trend line, in the first cell only, since the second cell draws :petal-length and :petal-width; a layer that fits no cell is drawn in every cell (see Pose Rules, Rules LP2 and LP3, for the whole rule):

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

marginal

[pose side]

[pose side layer-type]

[pose side layer-type opts]

Add a marginal panel beside a leaf pose: a distribution of one of the pose’s columns, drawn in a thin panel that shares the main panel’s axis for that column and carries its own value scale.

  • (marginal pose :top) – a density of the :x column, above.

  • (marginal pose :right) – a density of the :y column, to the right, drawn on its side.

  • (marginal pose :top :histogram) – a histogram instead.

  • (marginal pose :right :density {:size 0.3}) – a thicker panel.

:size is the marginal’s share of the height for :top and of the width for :right, 0.25 by default, and the only key the last map takes; any other reports an error. This map holds the marginal panel’s own setting, not a mapping: :size here is not the aesthetic. The marginal’s ticks and axis title along the shared axis are dropped, since the main panel’s axis describes both, and the two drawing areas are aligned so a value sits at the same place in each.

A :right marginal is drawn under pj/coord :flip, so its value axis runs across the panel and its baseline stands at the left edge, against the main panel.

A second layer added to the pose is drawn on the pose’s panel; a marginal is drawn beside that panel, on a value axis of its own.

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/marginal :top))
density0.00.20.4sepal width4.55.05.56.06.57.07.58.02.02.53.03.54.04.5sepal length

:histogram draws the distribution as bars instead, and :size sets the marginal’s share of the height:

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

:right describes the pose’s :y column in a strip beside the panel, drawn on its side:

(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width)
    (pj/marginal :right))
sepal length4.55.05.56.06.57.07.58.02.02.53.03.54.04.5density0.00.51.0sepal width

Rendering

plot

[pose]

[pose opts]

Render a pose to a figure. The format keyword in the pose’s :opts ({:format :svg} – default; {:format :bufimg} for raster PNG via Java2D; or any other registered backend) selects which membrane->plot defmethod runs.

On a composite pose, leaves are rendered individually and tiled via the layout in the resolved chrome, in the same chosen format. The pose flows through the canonical pose -> draft -> plan -> membrane -> plot pipeline for both leaf and composite shapes. pj/plot is a literal composition of the public atomic steps:

(let [pose (->pose x) opts (:opts pose {}) fmt (or (:format opts) :svg) plan (-> pose pose->draft draft->plan)] (-> plan (plan->membrane opts) (membrane->plot fmt opts)))

Plan-derived dimensions ride as record fields on the membrane (accessed via membrane.ui/width/membrane.ui/height); the title rides as :plotje/title. membrane->plot reads them from there.

Raw data (a dataset or a bare collection of values) is given a default mapping first, as pj/infer-mapping gives one, so (plot data) renders the inferred default instead of a blank figure.

  • (plot pose)
  • (plot pose {:width 800 :title "My Plot"})
  • (plot pose {:format :bufimg}) – returns a BufferedImage.

See the Customization notebook for options (title, theme, tooltip, brush, legend position, palette).

(-> tiny
    (pj/lay-point :x :y))
yx1234512345

pj/plot (and the other terminal steps pj/save, pj/draft, pj/plan, pj/membrane) also accept raw data directly, giving it a default mapping first – no explicit pj/pose needed:

(pj/plot {:height [150 160 170 175]
          :weight [50 60 72 78]})
weightheight150152154156158160162164166168170172174176505560657075

options

[pose opts]

Set plot-level options (title, labels, width, height, etc.). A later value replaces an earlier one, except :theme and :config, whose settings combine key by key – as a composite’s options combine with a cell’s. :width and :height are coerced to long (rounded) so the plan carries integer dimensions through to render. On a composite pose the options attach to the root so every descendant leaf inherits them at plan time.

Set render options on a pose:

(-> tiny
    (pj/lay-point :x :y)
    (pj/options {:width 400 :height 200 :title "Twice as wide as tall"}))
Twice as wide as tallyx1234524

Predicates

pose?

[x]

Return true if x is a pose-shaped plain map: one carrying :layers, :poses, or a map-valued :mapping.

Check whether a value is a pose (leaf or composite):

(pj/pose? (-> tiny
              (pj/pose :x :y)
              pj/lay-point))
true

plan?

[x]

Return true if x is a plan (leaf or composite) – the resolved geometry returned by pj/plan.

Check whether a value is a plan (from pj/plan):

(pj/plan? (pj/plan (pj/lay-point tiny :x :y)))
true

leaf-plan?

[x]

Return true if x is a leaf plan (single-pose resolved geometry).

Check whether a plan is a leaf (single-panel resolved geometry). A non-composite plan from a leaf pose is a leaf plan:

(pj/leaf-plan? (pj/plan (pj/lay-point tiny :x :y)))
true

composite-plan?

[x]

Return true if x is a composite plan (a tree of sub-plots with shared chrome).

Check whether a plan is a composite (a tree of sub-plots, returned by pj/plan on a composite pose like one from pj/arrange):

(pj/composite-plan?
 (pj/plan (pj/arrange [(pj/lay-point tiny :x :y)
                       (pj/lay-point tiny :x :y)])))
true

draft?

[x]

Return true if x is a draft – the intermediate representation produced by pj/pose->draft (and so by pj/draft). A draft is either a LeafDraft record (leaf pose) or a CompositeDraft record (composite pose). Used by cross-stage misuse guards on pj/plan and pj/plot.

Check whether a value is a draft (from pj/draft). True for both LeafDraft records and CompositeDraft records:

(pj/draft? (pj/draft (pj/lay-point tiny :x :y)))
true

leaf-draft?

[x]

Return true if x is a leaf draft (a LeafDraft record carrying :layers – a vector of layer maps – and :opts – the pose-level options that flow into the plan stage).

Check whether a draft is a leaf (a LeafDraft record carrying :layers and :opts, returned by pj/draft on a leaf pose):

(pj/leaf-draft? (pj/draft (pj/lay-point tiny :x :y)))
true

composite-draft?

[x]

Return true if x is a composite draft (a tree of sub-drafts with shared chrome-spec, returned by pj/draft on a composite pose).

Check whether a draft is a composite (a tree of sub-drafts, returned by pj/draft on a composite pose):

(pj/composite-draft?
 (pj/draft (pj/arrange [(pj/lay-point tiny :x :y)
                        (pj/lay-point tiny :x :y)])))
true

plan-layer?

[x]

Return true if x is a plan-layer (resolved geometry for one mark).

Check whether a value is a resolved plan layer:

(pj/plan-layer? (first (:layers (first (:panels (pj/plan (pj/lay-point tiny :x :y)))))))
true

layer-type?

[x]

Return true if x is a layer type (mark + stat + position bundle from the registry).

Check whether a value is a registered layer-type map:

(pj/layer-type? (pj/layer-type-lookup :point))
true

membrane?

[x]

Return true if x is a PlotjeMembrane – the value returned by pj/plan->membrane and pj/membrane. A PlotjeMembrane is a Membrane UI component (implements IOrigin, IBounds, IChildren) carrying the rendered drawables and plan-derived width/height; the plot title rides as :plotje/title.

Check whether a value is a PlotjeMembrane – the value returned by pj/plan->membrane and pj/membrane:

(pj/membrane? (pj/membrane (pj/lay-point tiny :x :y)))
true

series-mapping?

[v]

True of a mapping value that asks for a series.

Check whether a mapping value is a series. A vector of columns does, and one column does not:

[(pj/series-mapping? [:revenue :cost])
 (pj/series-mapping? :revenue)]
[true false]

series-mapping

The series a mapping value asks for, as {:cols [...] :as label}, or nil where it asks for none. See pose/series-mapping.

The series a mapping value names – its columns, and the name of the key column:

(pj/series-mapping {:series [:revenue :cost] :as :measure})
{:cols [:revenue :cost], :as :measure}

Inspection

draft

[pose]

[pose opts]

Resolve raw input into a draft. Literal composition of the atomic steps: (-> x ->pose pose->draft). The 2-arity folds opts into the pose with pj/options first, mirroring pj/plan and pj/plot: (-> x ->pose (options opts) draft).

Raw data (a dataset or a bare collection of values) is given a default mapping first, as pj/infer-mapping gives one, so (draft data) works without an explicit pj/pose call.

For a leaf pose, returns a LeafDraft record (:layers is a vector of flat maps, one per applicable layer with merged scope; :opts carries the pose-level options that flow into the plan stage). For a composite pose, and for a leaf with a facet over columns, which is drawn as one cell per column, returns a CompositeDraft carrying per-leaf drafts (each with the options the arrangement decided for its cell – which axes it shares and which ticks, axis titles and legends it suppresses), the resolved chrome geometry, and the layout (path -> rect). Shared domains are not in the draft: pj/draft->plan measures each cell and pools the extents of the axes it shares.

  • (draft pose)
  • (draft pose {:width 800 :title "Plot"})

Flatten a pose into a draft – a LeafDraft record holding :layers (one map per applicable layer, with all scope merged) and :opts (pose-level options). Useful for inspecting exactly what the plan stage will consume:

(-> (rdatasets/datasets-iris)
    (pj/pose :sepal-length :sepal-width)
    pj/lay-point
    pj/draft
    kind/pprint)
{:layers
 [{:x :sepal-length,
   :y :sepal-width,
   :mark :point,
   :stat :identity,
   :layer-type :point,
   :data
   https://vincentarelbundock.github.io/Rdatasets/csv/datasets/iris.csv [150 7]:

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

plan

[pose]

[pose opts]

Convert a pose into a plan. Literal composition of the atomic steps: (-> x ->pose pose->draft draft->plan). The 2-arity folds opts into the pose with pj/options first: (-> x ->pose (options opts) plan).

Raw data (a dataset or a bare collection of values) is given a default mapping first, as pj/infer-mapping gives one, so (plan data) works without an explicit pj/pose call.

For a leaf pose, returns a Plan record, with one panel per category where the pose is faceted by a column. For a composite pose, and for a leaf with a facet over columns, which is drawn as one cell per column, returns a CompositePlan record with :sub-plots tying each leaf path to its rect and sub-plan, plus :chrome carrying the resolved layout geometry (title-band, grid-rect, strip labels, shared-legend spec).

  • (plan pose)
  • (plan pose {:title "My Plot"})

Returns the intermediate plan data structure:

(def plan1 (-> tiny
               (pj/lay-point :x :y)
               pj/plan))
plan1
{:panels
 [{:coord :cartesian,
   :y-domain [0.8 5.2],
   :x-scale {:type :linear},
   :x-domain [0.8 5.2],
   :x-ticks
   {:values [1.0 2.0 3.0 4.0 5.0],
    :labels ["1" "2" "3" "4" "5"],
    :categorical? false},
   :col 0,
   :layers
   [{:mark :point,
     :style {:opacity 0.75, :radius 3.0},
     :alpha-scale nil,
     :y-domain [1 5],
     :x-domain [1 5],
     :size-scale nil,
     :fixed-tooltip nil,
     :alpha-drawn? nil,
     :groups
     [{:color [0.2 0.2 0.2 1.0], :xs #tech.v3.dataset.column<int64>[5]
:x
[1, 2, 3, 4, 5], :ys #tech.v3.dataset.column<int64>[5]
:y
[2, 4, 1, 5, 3], :row-indices #tech.v3.dataset.column<int64>[5]
:__row-idx
[0, 1, 2, 3, 4]}],
     :size-drawn? nil}],
   :y-scale {:type :linear},
   :y-ticks
   {:values [1.0 2.0 3.0 4.0 5.0],
    :labels ["1" "2" "3" "4" "5"],
    :categorical? false},
   :row 0}],
 :width 600,
 :height 400,
 :shape-legend nil,
 :caption nil,
 :total-width 600.0,
 :legend-position :none,
 :layout-type :single,
 :layout
 {:subtitle-pad 0,
  :legend-w 0,
  :caption-pad 0,
  :y-label-pad 42.5,
  :legend-h 0.0,
  :title-pad 0,
  :strip-h 0,
  :x-label-pad 38,
  :strip-w 0.0},
 :grid {:rows 1, :cols 1},
 :legend nil,
 :panel-height 362.0,
 :title nil,
 :y-label "y",
 :alpha-legend nil,
 :x-label "x",
 :y-label-lines ["y"],
 :subtitle nil,
 :panel-width 557.5,
 :x-label-lines ["x"],
 :size-legend nil,
 :total-height 400.0,
 :tooltip false,
 :margin 10}

frames

[plan-or-pose]

Where a plot’s panels sit on the canvas, and how to get between data space and drawing space.

Takes a plan or a pose; a pose is planned first. Returns a map:

  • :canvas – [x y width height] of the whole image, in drawing units
  • :panels – one entry per panel, each carrying :row, :col, :coord, :x-domain, :y-domain, :x-scale, :y-scale, :invertible? and :frames

A panel’s :frames names two rectangles, both [x y width height] in canvas coordinates: :panel-box (the panel with its axis margin) and :drawing-area (the background inside that margin, where data marks are clipped). The canvas is reported once, at the top: it belongs to the plot rather than to any panel.

The result contains no functions, so it can be printed, compared and read back from pr-str. To map between the spaces, pass a panel entry to pj/to-drawing or pj/to-data.

For a composite, every cell’s panels report canvas coordinates, so their rectangles can be compared without further arithmetic.

This is the same computation the renderer draws with. Use it to place your own annotations beside a plot, to compose a Plotje membrane with hand-built Membrane views, or to read a pointer position back as data.

  • (frames my-pose)
  • (-> my-plan frames :panels first :frames :drawing-area)

The whole result for this single-panel plot: the canvas, and one entry per panel with its row and column in the grid, its domains and scale specs, whether it can be mapped back to data, and its two frames.

(-> plan1
    pj/frames
    kind/pprint)
{:canvas [0.0 0.0 600.0 400.0],
 :panels
 [{:row 0,
   :col 0,
   :coord :cartesian,
   :x-domain [0.8 5.2],
   :y-domain [0.8 5.2],
   :x-scale {:type :linear},
   :y-scale {:type :linear},
   :invertible? true,
   :frames
   {:panel-box [42.5 0.0 557.5 362.0],
    :drawing-area [52.5 10.0 537.5 342.0]}}]}

The canvas is given once rather than on every panel: it belongs to the plot. Each panel’s rectangles are given in canvas coordinates, so they nest inside it and can be compared with each other directly. That holds for a composite too, where the panels come from separate sub-plans – here a canvas 700 wide holding two cells, whose panel boxes start at different x and both end inside the canvas:

(let [f (pj/frames (pj/arrange [(pj/lay-point tiny :x :y)
                                (pj/lay-line tiny :x :y)]
                               {:width 700 :height 300}))
      [_ _ cw ch] (:canvas f)
      boxes (mapv #(-> %
                       :frames
                       :panel-box)
                  (:panels f))
      inside? (fn [[x y w h]] (and (>= x 0) (>= y 0)
                                   (<= (+ x w) cw) (<= (+ y h) ch)))]
  {:canvas (:canvas f)
   :panel-boxes boxes
   :every-box-inside-the-canvas (every? inside? boxes)
   :panel-rectangle-keys (mapv #(vec (keys (:frames %))) (:panels f))})
{:canvas [0.0 0.0 700.0 300.0],
 :panel-boxes [[42.5 0.0 307.5 262.0] [392.5 0.0 307.5 262.0]],
 :every-box-inside-the-canvas true,
 :panel-rectangle-keys
 [[:panel-box :drawing-area] [:panel-box :drawing-area]]}

The result contains no functions, so it can be printed, compared and read back from pr-str. The two mappings below take a panel entry as their first argument.

to-drawing

[panel x y]

[panel data]

Where data values land on the canvas, for one panel of pj/frames.

Takes a panel entry – an element of (:panels (frames plot)) – and either one x and y, or a dataset of them with :x and :y columns. The dataset arity maps whole columns and builds the panel’s scales once, so it is the one to reach for when placing many of them.

  • (to-drawing panel 3.2 21.0) returns [x y] in canvas coordinates
  • (to-drawing panel {:x [3.2 4.0] :y [21.0 18.5]}) returns a dataset with the same two column names, now in canvas coordinates

A dataset rather than a collection of pairs because the two coordinates of a point share one index space, which a dataset states and two loose sequences only promise. Anything tc/dataset coerces works.

The result is in canvas coordinates, measured from the top left of the whole image. A {:in :drawing-area} layer measures from the drawing area’s own corner instead, so drawing these coordinates back means subtracting that corner first.

A pose, a plan or the whole frames map in the panel’s place reports an error naming which of them it got and the call that reaches a panel entry from there.

A categorical axis is a band scale, and it answers two kinds of value. A category sits at the middle of its band. A number is a place among the categories, counted from one: 1 is the first category, 1.5 sits halfway to the second, and on n categories the axis runs from 0.5 to n + 0.5. Anything else throws, naming the value and the categories it could have been – a category the axis does not carry, or a number past the ends of the axis. Under :coord :flip the arguments stay in data order, even though a panel entry’s :x-domain and :y-domain describe the drawn axes and the flip has already swapped those.

(pj/to-drawing (-> plan1
                   pj/frames
                   :panels
                   first)
               2 5)
[199.0909090909091 25.54545454545456]

to-data

[panel cx cy]

[panel data]

What data values the canvas coordinates name, for one panel of pj/frames. The direction an interaction reads: which value is under the pointer, which range a selection covers.

Throws under a coordinate system with no inverse. :polar maps x and y together to an angle and a radius, so a canvas position there does not name one pair of data values. A panel entry reports which case it is in :invertible?.

  • (to-data panel 412.0 88.5) returns [x y] in data values
  • (to-data panel {:x [412.0] :y [88.5]}) returns a dataset with the same two column names, now in data values

A continuous axis answers with numbers, so its column is :float64, and a coordinate pj/to-drawing produced comes back as the value it was given. A categorical axis answers with the category whose band holds the coordinate, so its column holds those – which is what an interaction wants, and is not the inverse of pj/to-drawing there: a place between two categories, such as 1.5, comes back as one of them.

A pose, a plan or the whole frames map in the panel’s place reports an error naming which of them it got and the call that reaches a panel entry from there.

Many data values at once go in and come back as a dataset:

(pj/to-drawing (-> plan1
                   pj/frames
                   :panels
                   first)
               {:x [2 3] :y [5 6]})

_unnamed [2 2]:

:x :y
199.09090909 25.54545455
321.25000000 -52.18181818

A value on a continuous axis survives the round trip:

(let [panel (-> plan1
                pj/frames
                :panels
                first)]
  (->> (pj/to-drawing panel 2 5)
       (apply pj/to-data panel)
       (mapv #(Math/round (double %)))))
[2 5]

A categorical axis gives back a category, which is what an interaction reads it for. So a place between two categories does not come back as that place: 1.5 goes in and the category whose band holds the coordinate comes back.

(let [panel (-> {:species ["setosa" "versicolor" "virginica"] :count [12.0 19.0 8.0]}
                (pj/lay-bar :species :count)
                pj/frames
                :panels
                first)]
  {:in 1.5
   :drawing-x (first (pj/to-drawing panel 1.5 10.0))
   :back (first (pj/to-data panel (first (pj/to-drawing panel 1.5 10.0)) 10.0))})
{:in 1.5, :drawing-x 228.66666666666669, :back "versicolor"}

svg-summary

[svg-or-pose]

[svg-or-pose theme]

Extract structural summary from SVG hiccup for testing. Returns a map of what the SVG draws – :width, :height, :panels, :points, :lines, :dashed-lines, :dash-patterns, :polygons, :tiles, :visible-tiles, :texts, :bold-texts, :italic-texts, :label-boxes and :clips, and the sets :sizes, :colors, :alphas and :shapes of the values the marks are drawn with – useful for asserting plot structure. Accepts SVG hiccup, or anything pj/plot accepts, which is rendered to SVG first: a pose, or raw data, drawn as pj/plot draws it. Anything else is reported by pj/plot.

  • (svg-summary (plot fr)) – summary of rendered SVG.
  • (svg-summary my-pose) – auto-renders pose (leaf or composite).
(-> (rdatasets/datasets-iris)
    (pj/lay-point :sepal-length :sepal-width {:color :species})
    pj/svg-summary)
{:sizes #{3.0},
 :bold-texts 0,
 :italic-texts 0,
 :dash-patterns #{},
 :texts
 ["sepal width"
  "sepal length"
  "species"
  "setosa"
  "versicolor"
  "virginica"
  "4.5"
  "5.0"
  "5.5"
  "6.0"
  "6.5"
  "7.0"
  "7.5"
  "8.0"
  "2.0"
  "2.5"
  "3.0"
  "3.5"
  "4.0"
  "4.5"],
 :width 600,
 :lines 0,
 :colors #{"none" "rgb(228,26,28)" "rgb(55,126,184)" "rgb(77,175,74)"},
 :points 150,
 :label-boxes 0,
 :alphas #{0.75},
 :dashed-lines 0,
 :clips 1,
 :tiles 0,
 :polygons 0,
 :visible-tiles 0,
 :panels 1,
 :height 400,
 :shapes #{:rect}}

valid-pose?

[pose]

Check if a pose conforms to the Malli schema.

  • (valid-pose? (lay-point data :x :y)) – true if valid.

The schema is structural and deliberately permissive: it says what shape a pose has, not whether the columns it names are in the data. A pose built by pj/pose, pj/lay-*, pj/options, pj/facet, pj/arrange, pj/coord or pj/scale conforms by construction; the check is for a pose that has been reached into and changed, which is the one place the constructors cannot speak for.

(pj/valid-pose? (pj/lay-point tiny :x :y))
true

explain-pose

[pose]

Explain why a pose does not conform to the Malli schema. Returns nil if valid, or a Malli explanation map if invalid.

  • (explain-pose (assoc (lay-point data :x :y) :layers {}))
(pj/explain-pose (pj/lay-point tiny :x :y))
nil

valid-plan?

[plan]

Check if a plan conforms to the Malli schema.

  • (valid-plan? (plan pose)) – true if valid.
(pj/valid-plan? plan1)
true

explain-plan

[plan]

Explain why a plan does not conform to the Malli schema. Returns nil if valid, or a Malli explanation map if invalid.

  • (explain-plan (plan pose))
(pj/explain-plan plan1)
nil

Pipeline

The pipeline is a composition of single-step transitions. The user-facing functions (pj/draft, pj/plan, pj/membrane, pj/plot, pj/save) run the chain up through their stage: each lifts raw input with pj/->pose, applies pj/infer-mapping (a default mapping when the input is a bare dataset, a no-op on a built pose), then runs the single-step transitions. So each of them accepts raw data as well as a pose. The Architecture chapter shows the full composition.

Each step is independently callable, so you can stop the pipeline at any point to inspect the intermediate value.

membrane

[pose]

[pose opts]

Resolve a pose into a PlotjeMembrane. Literal composition of the atomic steps: (let [pose (->pose x), opts (:opts pose {})] (-> pose pose->draft draft->plan (plan->membrane opts))). The let lifts the pose once so the chain can pluck pose-level opts and pass them to plan->membrane. The 2-arity folds opts into the pose with pj/options first.

Returns a PlotjeMembrane – a Membrane UI component (implements IOrigin, IBounds, IChildren) carrying the rendered drawables plus plan-derived width and height; the title, when set, rides as :plotje/title. Render-time options (:tooltip, :theme, :color-values, :color-range, :color-midpoint) ride along on the pose’s :opts and reach plan->membrane through this call.

Useful for exploring rendering targets beyond the SVG and Java2D backends Plotje wires in today: any Membrane backend can consume the result of pj/membrane via the standard Membrane protocols.

Raw data (a dataset or a bare collection of values) is given a default mapping first, as pj/infer-mapping gives one, so (membrane data) works without an explicit pj/pose call.

  • (membrane pose)
  • (membrane pose {:tooltip true})

Resolve a pose into a PlotjeMembrane – a format-agnostic Membrane UI component (a record implementing IOrigin, IBounds, IChildren). Useful for exploring rendering targets beyond the SVG and Java2D backends Plotje provides, and for composing Plotje plots into larger Membrane interfaces. The Membranes chapter walks the record’s anatomy and the protocols.

(let [m (pj/membrane (pj/lay-point tiny :x :y))]
  {:membrane?    (pj/membrane? m)
   :width        (membrane.ui/width m)
   :height       (membrane.ui/height m)
   :record-keys  (sort (filter keyword? (keys m)))})
{:membrane? true,
 :width 600,
 :height 400,
 :record-keys (:drawables :height :width)}

->pose

[x]

[x caller]

Lift the input to a pose. The first atomic step of the pipeline. Polymorphic on input:

  • a pose-shaped map flows through pose-kind (validated, Kindly auto-render metadata attached); idempotent on input that already carries the metadata, so repeated lifts are cheap;

  • raw data (a dataset, vector of row maps, or column map) becomes a leaf pose with :data set and no mapping, run through prepare-pose so the Kindly metadata is attached.

Throws on nil or non-collection scalars. Use (pj/pose) for an explicit empty leaf instead of passing nil.

The optional caller argument names the public-facing function shown in error messages, so users see β€œpj/lay-point requires data…” rather than an internal helper name. Defaults to β€œpj/->pose”.

  • (->pose data) – raw dataset becomes a leaf pose
  • (->pose pose) – already a pose; idempotent lift
  • (->pose {:x :a :y :b}) – a mapping becomes a leaf carrying it, with no data, to be completed by pj/with-data or by the pose it is placed in

Lift raw input to a pose. Raw data (datasets, vectors of row maps, column maps) becomes an empty leaf pose with :data set; an existing pose flows through unchanged (idempotent). The first step of the pipeline.

(pj/pose? (pj/->pose tiny))
true

infer-mapping

[fr]

Infer and attach a default mapping to a pose that carries data but no mapping yet – the fresh leaf pj/->pose produces from raw input. :x, :y and :color are taken from the columns of data with one to three columns (1 column to :x, 2 columns to :x and :y, 3 columns add :color).

The default is written where neither the pose’s mapping nor any layer names an :x or a :y column, and where the first layer names no column, whatever later layers name. Where only a :y is named and a layer’s type draws only from two columns, the first column nothing names becomes :x. A :y is never filled in. A composite pose, and data of four or more columns, are returned unchanged, and so is a pose already filled in, so the step is idempotent and safe to include anywhere in a pipeline. The draft runs the same step on every leaf, cells of a composite included. This is the step that lets raw data render a default: the shortcuts pj/draft, pj/plan, pj/membrane, pj/plot and pj/save apply it to what they are given. pj/pose and pj/->pose write no mapping.

  • (-> data pj/->pose pj/infer-mapping) – lift, then default map
  • (pj/infer-mapping built-pose) – no-op on an already-mapped pose

The default-mapping step the shortcuts apply right after pj/->pose. On a fresh leaf (data, no mapping) it maps the first 1-3 columns to :x, :y, and :color:

(-> {:height [150 160 170] :weight [50 60 72]}
    pj/->pose
    pj/infer-mapping
    :mapping)
{:x :height, :y :weight}

It returns the pose unchanged where the pose’s mapping names an :x or a :y column, or where a layer names every column it draws, so it is safe anywhere in a pipeline. Here the layer names both columns, and the pose’s mapping is empty before and after:

(let [built (pj/lay-point tiny :x :y)]
  [(:mapping built)
   (:mapping (pj/infer-mapping built))])
[nil nil]

A mapping that names neither :x nor :y, such as {:color :group}, is filled in:

(-> tiny
    (pj/pose {:color :group})
    pj/infer-mapping
    :mapping)
{:x :x, :y :y, :color :group}

pose->draft

[pose]

Single-step transition: convert a pose into a draft. Dispatches on pose shape – a leaf pose becomes a LeafDraft (a record carrying :layers – a vector of one map per applicable layer with merged scope – and :opts – the pose-level options that flow into the plan stage); a composite pose, a leaf with a facet over columns, which is drawn as one cell per column, and a leaf faceted by one category with {:cols n}, whose panels are wrapped into rows of cells, become a CompositeDraft carrying per-leaf drafts (each with the options the arrangement decided for its cell – which axes it shares and which ticks, axis titles and legends it suppresses), the resolved chrome geometry, and the layout (path -> rect). Shared domains are not in the draft: pj/draft->plan measures each cell and pools the extents of the axes it shares.

  • (pose->draft (pj/lay-point data :x :y))

Single-step transition: pose to draft. Dispatches on shape – leaf poses produce LeafDraft records, composite poses produce CompositeDraft records.

(pj/leaf-draft?
 (pj/pose->draft (pj/lay-point tiny :x :y)))
true

plan->membrane

[plan-data]

[plan-data opts]

Convert a plan into a PlotjeMembrane – a Membrane UI component carrying the rendered drawables, plan-derived width and height, and the plot title.

The 1-arity uses no rendering options. The 2-arity takes an opts map with optional :tooltip, :theme, :color-values, etc.

The result implements membrane.ui IOrigin, IBounds, and IChildren, so width and height are accessible via (membrane.ui/width m) and (membrane.ui/height m). The title, when set, rides as :plotje/title. Future per-membrane attributes use the same :plotje/* namespaced-keyword convention. The shape is captured by the PlotjeMembraneSchema in scicloj.plotje.impl.membrane.

  • (plan->membrane (plan fr))
  • (plan->membrane (plan fr) {:tooltip true})
(def m1 (pj/plan->membrane plan1))
(pj/membrane? m1)
true

valid-membrane?

[membrane]

Check if a membrane conforms to the Malli schema.

  • (valid-membrane? (membrane pose)) – true if valid.
(pj/valid-membrane? m1)
true

explain-membrane

[membrane]

Explain why a membrane does not conform to the Malli schema. Returns nil if valid, or a Malli explanation map if invalid.

  • (explain-membrane (membrane pose))
(pj/explain-membrane m1)
nil

membrane->plot

[membrane-tree format opts]

Convert a PlotjeMembrane into a figure for the given format. Dispatches on format keyword; :svg is always available.

Reads width and height from the membrane via (membrane.ui/width m) / (membrane.ui/height m) (so any Membrane backend can introspect the canvas size), and the title from (:plotje/title m).

  • (membrane->plot (plan->membrane (plan pose)) :svg {})
(first (pj/membrane->plot m1 :svg {}))
:svg

plan->plot

[plan format opts]

Convert a plan into a figure for the given format. Dispatches on format keyword. Each renderer is a separate namespace that registers a defmethod; :svg is always available.

  • (plan->plot (plan fr) :svg {})
  • (plan->plot (plan fr) :bufimg {})
(first (pj/plan->plot plan1 :svg {}))
:svg

The draft->* family lets the same pipeline start from a draft instead of a fully-resolved plan. Useful when you have a draft in hand (for example from inspection) and want to skip re-running the layer-flattening step.

draft->plan

[draft]

Single-step transition: convert a draft into a plan. Dispatches on draft shape – a LeafDraft carries :layers and pose-level :opts that flow into plan/draft->plan; a CompositeDraft goes through compositor/composite-draft->plan (which uses the chrome-spec already baked in at draft emission).

Plan-stage opts (:width, :height, :title, …) ride on the draft itself – on the LeafDraft’s :opts for leaves, on the CompositeDraft’s chrome-spec for composites. Set them on the pose via pj/options before drafting.

  • (draft->plan (draft pose))
(def draft1 (pj/draft (pj/lay-point tiny :x :y)))
(pj/plan? (pj/draft->plan draft1))
true

draft->membrane

[draft]

[draft opts]

Compose draft -> plan -> membrane. The 2-arity takes an opts map for plan->membrane (e.g. {:tooltip true}).

Render-stage options set on the original pose via pj/options (:theme, :color-values, …) ride on the draft’s :opts and form the base; any opts passed here override them per key. This keeps the explicit pipeline consistent with pj/plot, which feeds the pose’s opts into the membrane stage.

  • (draft->membrane (draft pose))
  • (draft->membrane (draft pose) {:tooltip true})
(pj/membrane? (pj/draft->membrane draft1))
true

draft->plot

[draft format opts]

Compose draft -> plan -> plot for the given format.

Render-stage options set on the original pose via pj/options (:theme, :color-values, …) ride on the draft’s :opts and form the base; the passed opts override them per key.

  • (draft->plot (draft pose) :svg {})
  • (draft->plot (draft pose) :bufimg {})
(first (pj/draft->plot draft1 :svg {}))
:svg

Configuration

config

[]

Return the effective resolved configuration as a map. Merges: library defaults < plotje.edn < set-config! < *config*. Useful for inspecting which values are in effect.

  • (config) – show current resolved config.
(pj/config)
{:legend-font-size 10,
 :strict false,
 :validate true,
 :point-stroke "none",
 :title-offset 18,
 :min-panel-size 20,
 :label-offset 38,
 :label-font-size 13,
 :x-tick-spacing 60,
 :thousands-separator nil,
 :default-color "#333",
 :width 600,
 :legend-header-pad 20,
 :y-tick-spacing 40,
 :point-stroke-width 0,
 :decimal-separator nil,
 :legend-width 100,
 :legend-entry-height 18,
 :rule-color "#333",
 :theme {:bg "#E8E8E8", :grid "#F5F5F5", :font-size 11},
 :bin-method :sturges,
 :domain-padding 0.05,
 :strip-height 16,
 :point-opacity 0.75,
 :band-color "#7F7F7F",
 :line-width 2.5,
 :grid-stroke-width 0.6,
 :fit-text-domain true,
 :strip-font-size 11,
 :strip-labels :value,
 :title-font-size 15,
 :band-opacity 0.15,
 :bar-opacity 0.85,
 :height 400,
 :margin 10,
 :point-radius 3.0}

set-config!

[m]

Set global config overrides. Persists across calls until reset.

  • (set-config! {:color-values :dark2 :theme {:bg "#FFFFFF"}}) – override the categorical colours and the background.

  • (set-config! nil) – reset to defaults.

with-config

[config-map & body]

Execute body with thread-local config overrides. Overrides take precedence over set-config! and defaults, but plot options still win.

The overrides apply to what is rendered inside the body. A pose returned from the body is drawn under the configuration in effect when it is shown, as a notebook shows the value of a form; to keep the overrides, end the body in pj/plot.

  • (with-config {:theme {:bg "#FFF"}} (plot ...))
(pj/with-config {:color-values :pastel1}
  (:color-values (pj/config)))
:pastel1

pj/with-config applies to what is rendered inside its body. A pose returned from the body is drawn under the configuration in effect when it is shown, so end the body in pj/plot to keep the configuration:

(pj/with-config {:theme {:bg "#1a1a2e"}}
  (-> (rdatasets/datasets-iris)
      (pj/lay-point :sepal-length :sepal-width)
      pj/plot))
sepal widthsepal length4.55.05.56.06.57.07.58.02.02.53.03.54.04.5

Documentation Metadata

Three maps document the keys written at each level: configuration, plot options, and a layer’s mapping.

config-key-docs

Documentation metadata for configuration keys. Maps each config key to [category description]. Use with (pj/config) to build reference tables.

(count pj/config-key-docs)
46

plot-option-docs

Documentation for plot-level option keys. These are accepted by pj/options, pj/plan, and pj/plot but are inherently per-plot (text content or nested config override). Maps each key to [category description].

(count pj/plot-option-docs)
16

layer-mapping-docs

Documentation for the keys a pj/lay-* mapping accepts: aesthetics and layer settings such as :stat, :bins and :position. Maps each key to a description string.

(count pj/layer-mapping-docs)
57

The tables below document the aesthetics. pj/panel-aesthetic-docs describes the panel aesthetics, which a pose’s mapping takes and a layer’s mapping does not:

panel-aesthetic-docs

Documentation for the panel aesthetics – the mapping keys that send each value of a distinction to a panel of its own. Written on a pose, not on a layer. pj/facet writes them, given a column or a map whose :col or :row names categories. Maps each key to a description string.

(keys pj/panel-aesthetic-docs)
(:col :row)

pj/aesthetic-roles gives the role of each aesthetic:

aesthetic-roles

[]

What a distinction given to each aesthetic is put to work as, as a map from aesthetic to role.

  • :positional – the mark is placed by the value.

  • :appearance – the marks share a place and are told apart by how they look, and a legend says which is which.

  • :grouping – the marks share a place and are not told apart.

  • :panel – each value gets a panel of its own, told apart by a strip label. pj/facet writes these.

A role is not a category: a category is a value a categorical column holds, which is what a role is given.

A function rather than a value, as pj/shape-symbols is: the registry grows from one release to the next.

(select-keys (pj/aesthetic-roles) [:x :color :group :col])
{:x :positional, :color :appearance, :group :grouping, :col :panel}

pj/aesthetic-scales lists, for each aesthetic that has a scale, the scale types it can be read through and the keys its scale spec reads:

aesthetic-scales

What each aesthetic’s scale accepts, one entry per aesthetic that has a scale, in display order.

Each entry carries :aesthetic, the :types that aesthetic can be read through, and the spec :keys it reads beside :type and :domain, which belong to every scale. Both are ordered vectors, and aesthetics with the same capabilities are adjacent so a table can group them.

The panel aesthetics, :col and :row, come last with no types and no keys: the one setting they take is a :domain, which orders their panels.

The same tables pj/scale and a mapping’s :scale validate against, so a reference table built from this cannot drift from what they enforce. Use it as pj/config-key-docs is used.

(first pj/aesthetic-scales)
{:aesthetic :x,
 :types [:linear :log :categorical],
 :keys [:include :breaks :tick-labels :n-ticks :tick-spacing :label]}

pj/compound-key-aesthetics names the aesthetics that read several columns as one distinction:

compound-key-aesthetics

[]

The aesthetics that read several columns as one distinction, united, as a set. Every other aesthetic that takes a column reports a vector as several columns where one goes.

{:group [:part :dimension]} is one grouping keyed on the pair, and {:col [:part :dimension]} draws a panel per combination the data holds – while {:color [:part :dimension]} reports an error: a vector of columns where one goes is read as a series, which is written on :x or :y. The three spellings of a vector read alike: bare, {:series [...]} and {:column [...]}.

The same set the check reads, so a table built from this cannot drift from what is enforced. Use it as pj/aesthetic-scales is used.

A function rather than a value, as pj/aesthetic-roles is: the registry grows from one release to the next.

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

pj/shape-palette lists the shape symbols assigned to categories, in order. Each of them is a symbol pj/shape-symbols accepts:

shape-palette

[]

The symbols assigned to categories automatically, in order. A plot with more categories than these repeats a symbol, so two categories cannot be told apart, and that warns at plan time.

Published apart from pj/shape-symbols because the two answer different questions: this is what a plot draws when you say nothing, and pj/shape-symbols is what you may write. Adding to this one changes which symbol every existing plot gives each category; adding to the other takes nothing away.

A function rather than a value, as pj/config is.

(pj/shape-palette)
[:circle :square :triangle :diamond :triangle-down :plus :cross]

Layer Type Registry

layer-type-lookup

[k]

Look up a registered layer type by keyword. Returns the layer-type map (with :mark, :stat, :position, :doc), or nil if not found.

  • (layer-type-lookup :histogram) returns {:mark :bar, :stat :bin, ...}.
(pj/layer-type-lookup :smooth)
{:mark :line,
 :stat :loess,
 :accepts
 [:confidence-band
  :level
  :bootstrap-resamples
  :bandwidth
  :size
  :stroke-dash
  :dx
  :dy],
 :doc
 "Smoothed trend line -- defaults to LOESS; pass {:stat :linear-model} for OLS.",
 :column-counts #{2}}

registered-layer-types

[]

Return all registered layer types as a map of keyword -> layer-type map. Useful for generating documentation tables.

(count (pj/registered-layer-types))
26
(first (pj/registered-layer-types))
[:smooth
 {:mark :line,
  :stat :loess,
  :accepts
  [:confidence-band
   :level
   :bootstrap-resamples
   :bandwidth
   :size
   :stroke-dash
   :dx
   :dy],
  :doc
  "Smoothed trend line -- defaults to LOESS; pass {:stat :linear-model} for OLS.",
  :column-counts #{2}}]

Documentation Helpers

Query the self-documenting dispatch tables for any extensible concept.

stat-doc

[k]

Return the prose description for a stat keyword. Returns "(no description)" if no [:key :doc] defmethod is registered.

  • (stat-doc :bin) returns "Bin numerical values into ranges".
(pj/stat-doc :linear-model)
"Linear model -- OLS regression line + optional confidence band"

mark-doc

[k]

Return the prose description for a mark keyword. Returns "(no description)" if no [:key :doc] defmethod is registered.

  • (mark-doc :point) returns "Filled circle".
(pj/mark-doc :point)
"Filled circle"

position-doc

[k]

Return the prose description for a position keyword. Returns "(no description)" if no [:key :doc] defmethod is registered.

  • (position-doc :dodge) returns "Shift groups side-by-side within a band".
(pj/position-doc :dodge)
"Shift groups side-by-side within a band"

scale-doc

[k]

Return the prose description for a scale keyword. Returns "(no description)" if no [:key :doc] defmethod is registered.

  • (scale-doc :linear) returns "Continuous linear mapping".
(pj/scale-doc :linear)
"Continuous linear mapping"

coord-doc

[k]

Return the prose description for a coordinate type keyword. Returns "(no description)" if no [:key :doc] defmethod is registered.

  • (coord-doc :polar) returns "Radial mapping: x->angle, y->radius".
(pj/coord-doc :cartesian)
"Standard x-right, y-up mapping"

membrane-mark-doc

[k]

Return the prose description for how a mark renders to membrane drawables. Returns "(no description)" if no [:key :doc] defmethod is registered.

  • (membrane-mark-doc :point) returns "Translated colored rounded-rectangles".
(pj/membrane-mark-doc :point)
"Translated colored rounded-rectangles"

Export

save

[pose path]

[pose path opts]

Save a plot to a file. Format resolution, in precedence order: 1. :format in the 3-arity opts map wins (must be :svg or :png). 2. :format on the pose’s :opts (:svg or :png; legacy :bufimg is translated to :png). 3. Otherwise inferred from the path extension (.svg -> :svg, .png -> :png). 4. Default :svg.

When the resolved format and the path extension disagree, prints a warning – the file still gets the bytes the resolved format produces, but the extension is misleading.

The save vocabulary names the file format. The plot vocabulary (pj/plot’s :format) names the JVM return type – :svg for hiccup, :bufimg for a Java2D BufferedImage. A pose-level :format flows into both contexts; save reinterprets :bufimg as :png because the file on disk is a PNG.

Arguments:

  • pose – a pose, or raw data (a dataset or a bare collection of values), which is given a default mapping first, as pj/infer-mapping gives one.

  • path – file path (string or java.io.File).

  • opts – same options as plot, but :format accepts only :svg or :png.

Tooltip and brush interactivity are not included in saved files.

Returns the written file as a java.io.File carrying :kind/image metadata, so evaluating a pj/save call in a notebook also shows the saved chart. The file prints as its path and compares equal to a plain java.io.File on the same path, so (str (pj/save ...)) still gives the path string.

  • (save my-pose "plot.svg") – SVG.
  • (save my-pose "plot.png") – inferred PNG.
  • (save my-pose "plot.svg" {:format :png}) – opts override (warns).

Save a plot to an SVG file:

(let [path (str (java.io.File/createTempFile "plotje-example" ".svg"))]
  (-> (rdatasets/datasets-iris)
      (pj/lay-point :sepal-length :sepal-width {:color :species})
      (pj/save path {:title "Iris Export"}))
  (.contains (slurp path) "<svg"))
true

Save a plot to a PNG file. Extension inference picks the raster backend; the file starts with the PNG signature, the eight bytes that open every PNG file:

(let [path (str (java.io.File/createTempFile "plotje-example" ".png"))]
  (-> (rdatasets/datasets-iris)
      (pj/lay-point :sepal-length :sepal-width {:color :species})
      (pj/save path))
  (with-open [in (java.io.FileInputStream. path)]
    (let [bs (byte-array 8)]
      (.read in bs)
      (mapv #(bit-and ^int % 0xFF) (vec bs)))))
[137 80 78 71 13 10 26 10]

Pass {:format :png} explicitly when the path’s extension does not match the desired format, or when it is built dynamically:

(let [path (str (java.io.File/createTempFile "plotje-example" ".out"))]
  (-> (rdatasets/datasets-iris)
      (pj/lay-point :sepal-length :sepal-width {:color :species})
      (pj/save path {:format :png}))
  (with-open [in (java.io.FileInputStream. path)]
    (let [bs (byte-array 4)]
      (.read in bs)
      (mapv #(bit-and ^int % 0xFF) (vec bs)))))
[137 80 78 71]

Retired

Public functions kept so that code written for an earlier release still runs. (pj/overlay pose) returns the pose unchanged and prints a warning, and (pj/overlay pose false) reports an error. pj/facet-grid prints a warning and returns the pose pj/facet writes for the same grid. pj/cross prints a warning and returns its pairs of columns; (pj/matrix data xs ys) draws the grid of every :x column against every :y column. pj/layer-option-docs is the earlier name of pj/layer-mapping-docs.

overlay

[pose-or-data]

[pose-or-data on?]

Retired. The layers of a pose share one panel, so (pj/overlay pose) returns the pose unchanged and warns, or reports an error under :strict as the other retired names do.

(pj/overlay pose false) reports an error: separate panels come from a split over the columns, as in (pj/facet pose {:y [:a :b]}), or from separate poses given to pj/arrange.

The layers of a pose share one panel without pj/overlay, so pj/overlay returns the pose unchanged and prints a warning:

(-> {:cohort [:a :b :c] :growth [12 19 15] :tax [3 5 4]}
    (pj/lay-bar :growth :cohort)
    (pj/lay-bar :tax :cohort)
    pj/overlay
    pj/svg-summary
    :panels)
Notestdout
Warning: pj/overlay -- :overlay is retired. The layers of a pose share one panel without it: remove it. It is ignored.
1

facet-grid

[pose col-col row-col]

Retired. (pj/facet-grid my-pose :a :b) warns, or reports an error under :strict as the other retired names do, and returns (pj/facet my-pose {:col :a :row :b}), the pose the warning names. With nil on one side the warning names, and the call returns, the facet in the other direction alone: (pj/facet my-pose :a) or (pj/facet my-pose {:row :b}).

(pj/facet-grid pose :smoker :sex) returns the pose (pj/facet pose {:col :smoker :row :sex}) returns:

(let [tips-pose (pj/lay-point (rdatasets/reshape2-tips) :total-bill :tip)]
  (= (pj/facet-grid tips-pose :smoker :sex)
     (pj/facet tips-pose {:col :smoker :row :sex})))
Notestdout
Warning: pj/facet-grid is retired. Write (pj/facet pose {:col :smoker :row :sex}), which draws the same panels.
true

cross

[xs ys]

Deprecated: it will be removed in a future release. Builds a vector of [x y] pairs from two column-name sequences, and warns, or reports an error under :strict as the retired names do. A pair is no cell of pj/arrange, where a vector is a list of cells. For a grid of panels with the xs across and the ys down, write (pj/matrix data xs ys); for a panel per pair, write each pair as a mapping, {:x :a :y :c}.

  • (pj/cross [:a :b] [:c :d]) returns [[:a :c] [:a :d] [:b :c] [:b :d]].

A pair of columns is not a cell of pj/arrange, where a vector is a list of cells, so pj/cross returns its pairs and prints a warning that names pj/matrix:

(let [pairs (atom nil)
      printed (with-out-str
                (reset! pairs (pj/cross [:sepal-length :petal-length]
                                        [:sepal-width :petal-width])))]
  {:pairs (deref pairs)
   :warns-with-pj-matrix (some? (re-find #"pj/matrix" printed))})
{:pairs
 ([:sepal-length :sepal-width]
  [:sepal-length :petal-width]
  [:petal-length :sepal-width]
  [:petal-length :petal-width]),
 :warns-with-pj-matrix true}

pj/matrix draws the grid the pairs describe:

(-> (rdatasets/datasets-iris)
    (pj/pose {:color :species})
    (pj/matrix [:sepal-length :petal-length]
               [:sepal-width :petal-width]))
2.02.53.03.54.04.5680.00.51.01.52.02.5246sepal lengthpetal lengthsepal widthpetal widthspeciessetosaversicolorvirginica

layer-option-docs

Deprecated: the earlier name of pj/layer-mapping-docs, the same map. It will be removed in a future release.

pj/layer-option-docs is the same map as pj/layer-mapping-docs:

(identical? pj/layer-option-docs pj/layer-mapping-docs)
true
source: notebooks/plotje_book/api_reference.clj