23  Builders: trees

Builders drawing a tree or using one: a dendrogram of a clustering or a hierarchy, a node-link tree, a heatmap ordered by clustering, edges bundled along a tree, and sequences as rings (a flow sunburst). Each takes its data and an options map and returns an ordinary plot map; the tree functions it forwards to are shared groups (Shared options), the trees themselves come from the tree data functions.

(ns reference.builders-trees
  (:require [fastmath.ml.clustering :as cl]
            [fastmath.stats :as stats]
            [cljplot2.core :as plot]
            [cljplot2.data.tree :as tree]
            [cljplot2.describe :as describe]
            [notebook-utils :as nu]))

Data: Motor Trend car road tests (1974), R datasets package mtcars (Henderson & Velleman 1981); licence: Part of R (GPL-2 | GPL-3).

(def mtcars (take 16 (nu/dataset :mtcars)))
model mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21 6 160 110 3.9 2.62 16.46 0 1 4 4
Mazda RX4 Wag 21 6 160 110 3.9 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.32 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.44 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.46 20.22 1 0 3 1
Duster 360 14.3 8 360 245 3.21 3.57 15.84 0 0 3 4
Merc 240D 24.4 4 146.7 62 3.69 3.19 20 1 0 4 2
Merc 230 22.8 4 140.8 95 3.92 3.15 22.9 1 0 4 2
Merc 280 19.2 6 167.6 123 3.92 3.44 18.3 1 0 4 4
Merc 280C 17.8 6 167.6 123 3.92 3.44 18.9 1 0 4 4
Merc 450SE 16.4 8 275.8 180 3.07 4.07 17.4 0 0 3 3
Merc 450SL 17.3 8 275.8 180 3.07 3.73 17.6 0 0 3 3
Merc 450SLC 15.2 8 275.8 180 3.07 3.78 18 0 0 3 3
Cadillac Fleetwood 10.4 8 472 205 2.93 5.25 17.98 0 0 3 4
Lincoln Continental 10.4 8 460 215 3 5.424 17.82 0 0 3 4
(def variables [:mpg :disp :hp :drat :wt :qsec])

The cars’ variables as z-scores, a row vector per car, clustered with complete linkage (fastmath hclust):

(def standardized
  (let [moments (into {} (for [k variables :let [vs (map k mtcars)]] [k [(stats/mean vs) (stats/stddev vs)]]))]
    (mapv (fn [car] (mapv (fn [k] (let [[mu sd] (moments k)] (/ (- (double (k car)) (double mu)) (double sd))))
                          variables))
          mtcars)))
(def car-clustering (cl/hclust standardized {:method :complete}))
(def car-names (mapv :model mtcars))

A small hierarchy as rows of levels:

(def offices [{:region "Europe" :country "Poland" :city "Warsaw"} {:region "Europe" :country "Poland" :city "Krakow"}
              {:region "Europe" :country "France" :city "Paris"} {:region "Europe" :country "France" :city "Lyon"}
              {:region "Asia" :country "Japan" :city "Tokyo"} {:region "Asia" :country "Japan" :city "Osaka"}
              {:region "Asia" :country "India" :city "Delhi"}])
region country city
Europe Poland Warsaw
Europe Poland Krakow
Europe France Paris
Europe France Lyon
Asia Japan Tokyo
Asia Japan Osaka
Asia India Delhi
(def office-tree (tree/from-levels offices {:hierarchy [:region :country :city]}))

23.1 dendrogram

A dendrogram of a clustering (an hclust result, its observations named by :labels) or of a tree (levels or parents) - branches at their merge heights, leaves along one axis.

Option Type Default Description
:labels sequential of any value or nil the observations' indices names of an hclust result's observations, in order (one per observation)
:horizontal true or false or nil false leaves on the left, heights growing right (not circular)
:labels? true or false true leaf names along the leaf axis (circular - outward around the circle)
:group-labels? true or false or nil false names of the named groups at their nodes (level and parent trees)
:line-style map of keyword to any value or nil theme [:chart :dendrogram-branch] line options of the branches, merged over the default
(plot/render-image (plot/dendrogram car-clustering {:labels car-names :k 3 :title "complete linkage, 3 clusters"})
                   {:width 900 :height 420})

Horizontal, with thicker red branches (:line-style, merged over the default), and without leaf names (left); a hierarchy with its group names at their nodes (right):

(plot/render-image (plot/arrange [(plot/dendrogram car-clustering {:labels car-names :horizontal true :labels? false
                                                                   :line-style {:color [200 60 40] :width 2}
                                                                   :title ":horizontal, :labels? false, :line-style"})
                                  (plot/dendrogram office-tree {:horizontal false :group-labels? true
                                                                :title "a hierarchy, :group-labels? true"})]
                                 {:columns 2})
                   {:width 1000 :height 400})

The branches draw in the theme style [:chart :dendrogram-branch] (a line style - its colour, width and dash shown; the clustered heatmap’s trees too), the group names in the text role :dendrogram-group-label:

Option Type Default Description
:color a clojure2d color or :none [70.0 70.0 70.0 255.0] line colour (a mapped :color wins)
:width a non-negative number 1 line width in pixels
:dash :none, a dash style (:dashed :dot-dash :dot-dot-dash :dotted :long-dash :loose-dot :solid :two-dash) or a sequence of positive numbers or nil :none dash style of the line (a mapped :dash wins)

Thin blue branches through the theme:

(plot/render-image (plot/dendrogram car-clustering {:labels car-names
                                                    :theme {:chart {:dendrogram-branch {:color [40 90 160] :width 0.6}}}})
                   {:width 700 :height 380})

Shared options: Dendrogram layout (:k :circular :span); Builder options (:title :scales :theme).

23.2 tree

A node-link tree: a point per node, links from parents to children, names beside the nodes; tidy (by depth) or cluster (leaves aligned), cartesian or circular (the Node-link tree layout group).

Option Type Default Description
:labels? true or false true node names (cartesian - leaves right of their node, groups left; circular - leaf names outward)
:nodes? true or false true a point per node
:mapping map of keyword to any value or nil node aesthetics (:color, :size, :shape): accessors of the nodes (their row's columns, :depth, :leaf?, :name)
:node-style map of keyword to any value or nil theme [:chart :tree-node] scatter options of the nodes, merged over the default
:link-style map of keyword to any value or nil theme [:chart :tree-link] line options of the links, merged over the default
:labels sequential of any value or nil the observations' indices names of an hclust result's observations, in order (one per observation)
(plot/render-image (plot/tree office-tree) {:width 600 :height 360})

Nodes coloured by depth through :mapping, larger nodes (:node-style) and dashed links (:link-style) (left); circular, neither names nor points - only the links (middle); a clustering’s tree named by :labels (right):

(plot/render-image (plot/arrange [(plot/tree office-tree {:mapping {:color #(str (:depth %))}
                                                          :node-style {:size 12}
                                                          :link-style {:dash :dashed :color [90 90 90]}
                                                          :title ":mapping, :node-style, :link-style"
                                                          :scales {:color {:legend false}}})
                                  (plot/tree office-tree {:labels? false :nodes? false :circular true
                                                          :title ":circular true, no names or points"})
                                  (plot/tree car-clustering {:labels car-names :labels? true :nodes? true
                                                             :title "a clustering, :labels"})]
                                 {:columns 3})
                   {:width 1000 :height 420})

The theme styles of a node-link tree - nodes in [:chart :tree-node] (scatter), links in [:chart :tree-link] (line - its colour, width and dash shown), names in the text role :tree-label:

Option Type Default Description
:size a non-negative number 7 point size in pixels (a mapped :size wins)
:color a clojure2d color or :none [70.0 130.0 180.0 255.0] point colour (a mapped :color wins)
:stroke-color a clojure2d color or :none :white outline colour: a colour or :none
:stroke-width a non-negative number 1 outline width in pixels
:shape a shape character, keyword or shape map \O point shape (a mapped :shape wins)

Small dark nodes through the theme:

(plot/render-image (plot/tree office-tree {:theme {:chart {:tree-node {:size 5 :color [60 60 60] :stroke-color :none}}}})
                   {:width 600 :height 360})

Option Type Default Description
:color a clojure2d color or :none [176.0 176.0 176.0 255.0] line colour (a mapped :color wins)
:width a non-negative number 0.9 line width in pixels
:dash :none, a dash style (:dashed :dot-dash :dot-dot-dash :dotted :long-dash :loose-dot :solid :two-dash) or a sequence of positive numbers or nil :none dash style of the line (a mapped :dash wins)

Darker, thicker links and bold names through the theme:

(plot/render-image (plot/tree office-tree {:theme {:chart {:tree-link {:color [90 90 90] :width 2}}
                                                   :text {:tree-label {:font-style :bold}}}})
                   {:width 600 :height 360})

Shared options: Node-link tree layout (:layout :links :circular :span); Builder options (:title :scales :theme).

23.3 clustered-heatmap

Tiles of a value per row and column, rows and columns ordered by hierarchical clustering, their dendrograms beside the tiles; the data are long rows (:row, :col, :value accessors).

Option Type Default Description
:row (required) a keyword, a function or a categorical marker of one accessor of a row's tile row
:col (required) a keyword, a function or a categorical marker of one accessor of a row's tile column
:value (required) a keyword, a function or a categorical marker of one accessor of a row's tile value, a finite number
:method one of :single :complete :average :weighted :centroid :median :ward :ward-d :diana :complete fastmath hclust linkage of the rows and columns
:distance one of :euclidean :chebyshev :manhattan :canberra :earth-movers or a function :euclidean fastmath hclust distance: a keyword or a function of two double arrays
:row-tree? true or false true the rows' dendrogram right of the tiles (false - order only)
:col-tree? true or false true the columns' dendrogram above the tiles (false - order only)
:tree-size [a number in (0 1), a number in (0 1)] [0.2 0.2] [w h] - the dendrograms' share of the width (rows) and the height (columns), fractions in (0, 1)
(def car-scores (vec (for [[car row] (map vector car-names standardized) [k v] (map vector variables row)]
                       {:car car :variable (name k) :z v})))
car variable z
Mazda RX4 mpg 0.6750876206931093
Mazda RX4 disp -0.8010684219091876
Mazda RX4 hp -0.6554596090331999
Mazda RX4 drat 1.1283722620337149
Mazda RX4 wt -1.1502784754134987
Mazda RX4 qsec -1.1015230645561858
Mazda RX4 Wag mpg 0.6750876206931093
Mazda RX4 Wag disp -0.8010684219091876
Mazda RX4 Wag hp -0.6554596090331999
Mazda RX4 Wag drat 1.1283722620337149
Mazda RX4 Wag wt -0.838525042459661
Mazda RX4 Wag qsec -0.7741715999318604
Datsun 710 mpg 1.1090725197101083
Datsun 710 disp -1.2597353595104843
Datsun 710 hp -0.9790258770132912
Datsun 710 drat 1.014968014593141
Datsun 710 wt -1.517047220065073
Datsun 710 qsec 0.15527273712649395
Hornet 4 Drive mpg 0.7715287093635531
Hornet 4 Drive disp 0.06334234510864066
Hornet 4 Drive hp -0.6554596090331999
Hornet 4 Drive drat -0.7314573959917041
Hornet 4 Drive wt -0.4228537985212105
Hornet 4 Drive qsec 0.6404543721946926
Hornet Sportabout mpg 0.1205513608380552
Hornet Sportabout disp 0.9630351842496456
Hornet Sportabout hp 0.5817055332436202
Hornet Sportabout drat -0.5726914495749004
Hornet Sportabout wt -0.14777724003252984
Hornet Sportabout qsec -0.7741715999318604
Valiant mpg -0.024110272167610528
Valiant disp -0.2277347499075668
Valiant hp -0.7506261584391091
Valiant drat -1.4572445796113807
Valiant wt -0.12332599038909156
Valiant qsec 1.096408197921431
Duster 360 mpg -0.9403006145368302
Duster 360 disp 0.9630351842496456
Duster 360 hp 1.9140372249263495
Duster 360 drat -0.43660635264621106
Duster 360 wt 0.011155882649818772
Duster 360 qsec -1.4639479003902616
Merc 240D mpg 1.4948368743918843
Merc 240D disp -0.9183813117187501
Merc 240D hp -1.5690584833299286
Merc 240D drat 0.6520744227833027
Merc 240D wt -0.45341786057550826
Merc 240D qsec 0.967805836819018
Merc 230 mpg 1.1090725197101083
Merc 230 disp -0.9704223681004355
Merc 230 hp -0.9409592572509275
Merc 230 drat 1.1737339610099446
Merc 230 wt -0.5023203598623848
Merc 230 qsec 2.663018778623563
Merc 280 mpg 0.2411027216761104
Merc 280 disp -0.734032484875152
Merc 280 hp -0.40802658057783586
Merc 280 drat 1.1737339610099446
Merc 280 wt -0.14777724003252984
Merc 280 qsec -0.02593968079054295
Merc 280C mpg -0.09644108867044382
Merc 280C disp -0.734032484875152
Merc 280C hp -0.40802658057783586
Merc 280C drat 1.1737339610099446
Merc 280C wt -0.14777724003252984
Merc 280C qsec 0.32479403130694806
Merc 450SE mpg -0.43398489901699894
Merc 450SE disp 0.2203475660567769
Merc 450SE hp 0.6768720826495295
Merc 450SE drat -0.7541382454798196
Merc 450SE wt 0.6224371237357761
Merc 450SE qsec -0.5520402489367825
Merc 450SL mpg -0.21699244950849902
Merc 450SL disp 0.2203475660567769
Merc 450SL hp 0.6768720826495295
Merc 450SL drat -0.7541382454798196
Merc 450SL wt 0.2067658797973251
Merc 450SL qsec -0.43512901157095013
Merc 450SLC mpg -0.7233081650283313
Merc 450SLC disp 0.2203475660567769
Merc 450SLC hp 0.6768720826495295
Merc 450SLC drat -0.7541382454798196
Merc 450SLC wt 0.26789400390592055
Merc 450SLC qsec -0.20130653683928948
Cadillac Fleetwood mpg -1.880601229073661
Cadillac Fleetwood disp 1.9509332036985922
Cadillac Fleetwood hp 1.1527048296790756
Cadillac Fleetwood drat -1.071670138313427
Cadillac Fleetwood wt 2.065060852698634
Cadillac Fleetwood qsec -0.2129976605758723
Lincoln Continental mpg -1.880601229073661
Lincoln Continental disp 1.8450869873290623
Lincoln Continental hp 1.3430379284908942
Lincoln Continental drat -0.9129041918966233
Lincoln Continental wt 2.277786724596547
Lincoln Continental qsec -0.306526650468537
(plot/render-image (plot/clustered-heatmap car-scores {:row :car :col :variable :value :z
                                                       :scales {:color {:range :RColorBrewer/RdBu :midpoint 0
                                                                        :reverse true :title "z-score"}}})
                   {:width 700 :height 500})

The distances between rows and columns (:distance, here with average linkage) give different orders and trees:

(plot/render-image (plot/arrange [(plot/clustered-heatmap car-scores {:row :car :col :variable :value :z :method :average
                                                                      :distance :manhattan :title ":distance :manhattan"
                                                                      :scales {:color {:legend false}}})
                                  (plot/clustered-heatmap car-scores {:row :car :col :variable :value :z :method :average
                                                                      :distance :chebyshev :title ":distance :chebyshev"
                                                                      :scales {:color {:legend false}}})
                                  (plot/clustered-heatmap car-scores {:row :car :col :variable :value :z :method :average
                                                                      :distance :canberra :title ":distance :canberra"
                                                                      :scales {:color {:legend false}}})
                                  (plot/clustered-heatmap car-scores {:row :car :col :variable :value :z :method :average
                                                                      :distance :earth-movers
                                                                      :title ":distance :earth-movers"
                                                                      :scales {:color {:legend false}}})]
                                 {:columns 2})
                   {:width 1000 :height 800})

Only the rows’ tree, wider (:tree-size), columns ordered without their tree (left); Ward linkage with the default euclidean distance, no trees - only the order (right):

(plot/render-image (plot/arrange [(plot/clustered-heatmap car-scores {:row :car :col :variable :value :z
                                                                      :col-tree? false :tree-size [0.35 0.2]
                                                                      :title ":col-tree? false, :tree-size [0.35 0.2]"
                                                                      :scales {:color {:legend false}}})
                                  (plot/clustered-heatmap car-scores {:row :car :col :variable :value :z :method :ward
                                                                      :row-tree? false :col-tree? false
                                                                      :title ":method :ward, no trees"})]
                                 {:columns 2 :widths [1 1.15]})
                   {:width 1000 :height 450})

Shared options: Builder options (:title :scales :theme).

23.4 bundle

Hierarchical edge bundling: edges between the leaves of a tree, each bent along the tree path between its ends, leaves around a circle. Edges name their leaves by key - a tree/from-parents node’s id, else the leaf’s name (tree/from-levels, tree/from-hclust): here the office tree from levels, edges between cities.

Option Type Default Description
:alpha a number in [0 1] 0.4 opacity of the edges (leaf points and legend keys stay opaque)
:color-by-group? true or false true edges and leaves coloured by the top-level group of their (source) leaf, with a legend
:edge-color a clojure2d color or :none [70.0 110.0 180.0 255.0] colour of the edges when not coloured by group
:labels? true or false true leaf names outward around the circle
(def calls [{:from "Warsaw" :to "Paris"} {:from "Warsaw" :to "Tokyo"} {:from "Krakow" :to "Lyon"}
            {:from "Krakow" :to "Delhi"} {:from "Paris" :to "Osaka"} {:from "Lyon" :to "Tokyo"}
            {:from "Tokyo" :to "Delhi"} {:from "Osaka" :to "Warsaw"} {:from "Delhi" :to "Paris"}])
from to
Warsaw Paris
Warsaw Tokyo
Krakow Lyon
Krakow Delhi
Paris Osaka
Lyon Tokyo
Tokyo Delhi
Osaka Warsaw
Delhi Paris
(plot/render-image (plot/bundle calls office-tree {}) {:width 500 :height 500})

One edge colour, more opaque, without leaf names (left); coloured by group with the default translucency and names (right):

(plot/render-image (plot/arrange [(plot/bundle calls office-tree {:color-by-group? false :edge-color [120 60 160]
                                                                  :alpha 0.8 :labels? false
                                                                  :title ":color-by-group? false, :alpha 0.8"})
                                  (plot/bundle calls office-tree {:color-by-group? true :alpha 0.4 :labels? true
                                                                  :title ":color-by-group? true"})]
                                 {:columns 2 :widths [1 1.3]})
                   {:width 1000 :height 480})

The theme styles of edge bundling - edges in [:chart :bundle-edge] (line - its colour, width and dash shown), leaves in [:chart :bundle-leaf] (scatter):

Option Type Default Description
:color a clojure2d color or :none [69.0 117.0 180.0 255.0] line colour (a mapped :color wins)
:width a non-negative number 1 line width in pixels
:dash :none, a dash style (:dashed :dot-dash :dot-dot-dash :dotted :long-dash :loose-dot :solid :two-dash) or a sequence of positive numbers or nil :none dash style of the line (a mapped :dash wins)

Thicker edges through the theme:

(plot/render-image (plot/bundle calls office-tree {:theme {:chart {:bundle-edge {:width 2.5}}}})
                   {:width 500 :height 500})

Option Type Default Description
:size a non-negative number 3 point size in pixels (a mapped :size wins)
:color a clojure2d color or :none [69.0 117.0 180.0 180.0] point colour (a mapped :color wins)
:stroke-color a clojure2d color or :none :none outline colour: a colour or :none
:stroke-width a non-negative number 1 outline width in pixels
:shape a shape character, keyword or shape map \O point shape (a mapped :shape wins)

Large square leaves through the theme:

(plot/render-image (plot/bundle calls office-tree {:theme {:chart {:bundle-leaf {:size 8 :shape \s}}}})
                   {:width 500 :height 500})

Shared options: Edge bundling (:from :to :beta); Builder options (:title :scales :theme).

23.5 sequences

A flow sunburst: sequences of steps (a string of steps with a separator) as rings from the centre, every step coloured by its name wherever it occurs, the end of a sequence a step of its own.

Option Type Default Description
:inner a finite number, >= 0, < 1 0.3 radius of the centre hole, a fraction of the outer one
:labels? true or false false step names in the cells that fit
:keep-end? true or false true the end marker a step of its own, coloured and in the legend (false - sequences that end are their group's grey remainder)
(def visits [{:sequence "home-search-product-end" :n 30} {:sequence "home-product-cart-end" :n 25}
             {:sequence "home-search-end" :n 20} {:sequence "home-end" :n 15}
             {:sequence "home-help-search-product-cart-end" :n 10} {:sequence "home-product-end" :n 18}])
sequence n
home-search-product-end 30
home-product-cart-end 25
home-search-end 20
home-end 15
home-help-search-product-cart-end 10
home-product-end 18
(plot/render-image (plot/sequences visits {:value :n}) {:width 500 :height 450})

A smaller hole - more room for the rings - and the step names in the cells where they fit (a larger image):

(plot/render-image (plot/sequences visits {:value :n :inner 0.1 :labels? true :title ":inner 0.1, :labels? true"})
                   {:width 700 :height 600})

Ending sequences left as their group’s grey remainder, the end not a step of its own:

(plot/render-image (plot/sequences visits {:value :n :keep-end? false :title ":keep-end? false"})
                   {:width 550 :height 450})

The cells draw in the theme style [:chart :sequences-cell] (a partition style over [:chart :partition]):

Option Type Default Description Group
:border-color a clojure2d color or :none :white cell border colour
:border-width a non-negative number 0.3 cell border width in pixels
:pattern a pattern name (:back-hatch :cross :dense-dots :diagonal-cross :dots :hatch :horizontal :solid :vertical) or a pattern map :solid pattern drawn over the fill (a mapped :pattern wins) Fill patterns
:pattern-color :darker or a clojure2d color or :none :darker pattern ink: a colour, :none or :darker (the darkened fill) Fill patterns

Thick white cell borders through the theme:

(plot/render-image (plot/sequences visits {:value :n :theme {:chart {:sequences-cell {:border-width 2}}}})
                   {:width 500 :height 450})

Shared options: Sequences (:sequence :value :separator :end); Builder options (:title :scales :theme).

source: notebooks/reference/builders_trees.clj