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))
countspeciessetosaversicolorvirginica05101520253035404550

Colored (dodged)

Grouped (dodged) bars – count by day, colored by smoking status.

(-> (rdatasets/reshape2-tips)
    (pj/lay-bar :day {:color :smoker}))
countdaysmokerNoYesSunSatThurFri01020304050

Stacked

Same data, stacked instead of dodged.

(-> (rdatasets/reshape2-tips)
    (pj/lay-bar :day {:position :stack :color :smoker}))
countdaysmokerNoYesSunSatThurFri0102030405060708090

Proportions (100% stacked)

100% stacked bars – shows proportions instead of counts.

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

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}))
speciescount05101520253035404550setosaversicolorvirginica

(pj/coord :flip) turns a chart written upright, and draws the same bars:

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

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))
daycounttimeDinnerLunch0102030405060708090SunSatThurFri

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))
revenueproductwidgetgadgetgizmodoohickey050100150200250300350

Horizontal

Put the category on :y – no (pj/coord :flip) needed.

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

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))
productrevenue050100150200250300350doohickeywidgetgizmogadget

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]}))
productrevenue050100150200250300350doohickeywidgetgizmogadget

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))
productrevenue050100150200250300350doohickeywidgetgizmogadget

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}))
revenuedepartmentOffice SuppliesElectronicsHome GoodsSporting GearGarden ToolsToys050100150200250300350

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))
revenueproductwidgetgadgetgizmodoohickey050100150200250300350

Horizontal

Flipped for horizontal orientation.

(-> sales
    (pj/lay-lollipop :product :revenue)
    (pj/coord :flip))
productrevenue050100150200250300350widgetgadgetgizmodoohickey

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}))
revenueproductregionNorthSouthABCDEF020406080100120140160180200

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}))
revenueproductwidgetgadgetgizmodoohickey050100150200250300350

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}))
residualindex0510152025303540-0.8-0.6-0.4-0.20.00.20.40.60.8

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))
teambefore, afterbeforeafter50556065707580OpsSalesSupportResearch

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))
teambefore, afterbeforeafter50556065707580OpsSalesSupportResearch

See Also

  • Core Concepts – mappings and aesthetic vocabulary
  • Distributions – when comparing categories also means comparing their distributions

What’s Next

source: notebooks/plotje_book/ranking.clj