16 Ranking
Bar charts and their variants β comparing quantities across categories.
(ns plotje-book.ranking
(:require
;; Kindly -- notebook rendering protocol
[scicloj.kindly.v4.kind :as kind]
;; Tablecloth -- dataset manipulation
[tablecloth.api :as tc]
;; Rdatasets -- standard datasets
[scicloj.metamorph.ml.rdatasets :as rdatasets]
;; Plotje -- composable plotting
[scicloj.plotje.api :as pj]))(def sales {:product [:widget :gadget :gizmo :doohickey]
:revenue [120 340 210 95]})Count bars
pj/lay-bar with only a category column counts the rows in each category β the bar height is the number of occurrences.
Plain
Count occurrences of a categorical column.
(-> (rdatasets/datasets-iris)
(pj/lay-bar :species))Colored (dodged)
Grouped (dodged) bars β count by day, colored by smoking status.
(-> (rdatasets/reshape2-tips)
(pj/lay-bar :day {:color :smoker}))Stacked
Same data, stacked instead of dodged.
(-> (rdatasets/reshape2-tips)
(pj/lay-bar :day {:position :stack :color :smoker}))Proportions (100% stacked)
100% stacked bars β shows proportions instead of counts.
(-> (rdatasets/palmerpenguins-penguins)
(pj/lay-bar :island {:position :fill :color :species}))Horizontal
Name the category on :y and the counting bars run horizontally, with the counts along the x-axis.
(-> (rdatasets/datasets-iris)
(pj/lay-bar {:y :species}))(pj/coord :flip) turns a chart written upright, and draws the same bars:
(-> (rdatasets/datasets-iris)
(pj/lay-bar :species)
(pj/coord :flip))Both forms draw the categories bottom-to-top in data order. ggplot2βs coord_flip() also runs bottom to top, in the order of the factor levels rather than of the data. For a ranking chart where the biggest value should appear at the top, sort the data ascending before plotting, or give the category axis a :domain in the order to draw β both are shown under Ranked below.
Horizontal, colored
Colored bars, flipped.
(-> (rdatasets/reshape2-tips)
(pj/lay-bar :day {:color :time})
(pj/coord :flip))Value bars
Give pj/lay-bar a value column too and it uses those numbers directly as the bar heights β no counting. The data holds one row per bar. To draw a mean or a total per category from data with several rows per category, summarize it first with tc/group-by and tc/aggregate, as in Datasets.
Vertical
One bar per product; the bar height is the revenue.
(-> sales
(pj/lay-bar :product :revenue))Horizontal
Put the category on :y β no (pj/coord :flip) needed.
(-> sales
(pj/lay-bar :revenue :product))Ranked
A ranking chart is read down from the biggest, and the bars above are in whatever order the data happened to hold. Plotje draws the bands of a categorical y axis in data order, running bottom to top, so sorting the rows ascending by the value puts the biggest bar at the top. The same sort does the same thing for bars written upright and turned with (pj/coord :flip).
(def sales-ranked
(-> sales
tc/dataset
(tc/order-by :revenue :asc)))(-> sales-ranked
(pj/lay-bar :revenue :product))The order can also be written on the category axis, leaving the data as it is. A :domain on a categorical axis lists the categories in the order to draw them, bottom to top:
(-> sales
(pj/lay-bar :revenue :product)
(pj/scale :y {:domain [:doohickey :widget :gizmo :gadget]}))Under (pj/coord :flip), the categories are the dataβs :x, so the :domain goes on the :x scale, though the categories are drawn down the vertical axis:
(-> sales
(pj/lay-bar :product :revenue)
(pj/scale :x {:domain [:doohickey :widget :gizmo :gadget]})
(pj/coord :flip))Rotated labels
Horizontal bars are one way to fit long category names. To keep the bars vertical instead, rotate the x-tick labels with :x-tick-angle (see Customization for details, including :x-tick-label-pad):
(-> {:department ["Office Supplies" "Electronics" "Home Goods"
"Sporting Gear" "Garden Tools" "Toys"]
:revenue [120 340 210 95 160 80]}
(pj/lay-bar :department :revenue)
(pj/options {:x-tick-angle -45}))Lollipop
A stem and a dot in place of a bar β a lollipop chart draws the same comparison with less ink.
Vertical
(-> sales
(pj/lay-lollipop :product :revenue))Horizontal
Flipped for horizontal orientation.
(-> sales
(pj/lay-lollipop :product :revenue)
(pj/coord :flip))With a color column
Map a categorical column to :color to distinguish groups visually β here, products grouped by region.
(-> {:product ["A" "B" "C" "D" "E" "F"]
:revenue [120 95 150 80 200 110]
:region ["North" "South" "North" "South" "North" "South"]}
(pj/lay-lollipop :product :revenue {:color :region}))Without the dot
pj/lay-segment draws the stem alone. A segment runs from each rowβs :x and :y to its :x-end and :y-end; an end left out keeps the startβs value, so {:y-end 0} draws each stem from the value down to the zero line:
(-> sales
(pj/lay-segment :product :revenue {:y-end 0}))The x axis can hold numbers as well as categories. One stem per observation over its index is a stem plot, the shape of a residual or Cookβs distance (how much each observation moves a fitted regression) diagnostic:
(-> {:index (range 1 41)
:residual (map #(* (Math/sin %) (Math/exp (- (/ % 30.0)))) (range 1 41))}
(pj/lay-segment :index :residual {:y-end 0})
(pj/lay-rule-h {:y-intercept 0}))Dumbbell
A dumbbell chart compares two values for each category β a score before and after a change β by joining them with a line. Both ends of the segment can name columns: :x is where the segment starts and :x-end where it stops. A point layer on each column marks the two ends. The two point layers draw different :x columns on the same panel, and each takes a color and a legend entry of its own:
(-> {:team ["Ops" "Sales" "Support" "Research"]
:before [62 48 71 55]
:after [74 66 69 81]}
(pj/lay-segment :before :team {:x-end :after})
(pj/lay-point :before :team)
(pj/lay-point :after :team))The segment layer names :before on :x too, so it is drawn in the color of the before points. Writing :color "grey" on the segment layer draws the line grey, and the legend keeps the two point colors:
(-> {:team ["Ops" "Sales" "Support" "Research"]
:before [62 48 71 55]
:after [74 66 69 81]}
(pj/lay-segment :before :team {:x-end :after :color "grey"})
(pj/lay-point :before :team)
(pj/lay-point :after :team))See Also
- Core Concepts β mappings and aesthetic vocabulary
- Distributions β when comparing categories also means comparing their distributions
Whatβs Next
- Change Over Time β line charts, step functions, and stacked areas
- Configuration β control dimensions, palettes, and themes