Rubyvis - Example: Becker’s Barley

The Trellis display by Becker et al. helped establish small multiples as a “powerful mechanism for understanding interactions in studies of how a response depends on explanatory variables”. Here we reproduce a trellis of Barley yields from the 1930s, complete with main-effects ordering to facilitate comparison. These examples demonstrate Protovis’ support for data transformation via the nest operator.
Notice anything unusual about one of the sites? This anomaly led Becker et al. to suspect a major error with the data that went undetected for six decades.

require 'rubyvis'
# Nest yields data by site then year. */

# Compute yield medians by site and by variety. */
median=lambda {|data| 
       pv.median(data, lambda {|d| d[:yield]}) 

site = pv.nest($barley).
       key(lambda {|d| d[:site]}).

variety = pv.nest($barley).key(lambda {|d| d[:variety]}).rollup(median);

barley = pv.nest($barley)
    .key(lambda {|d| d[:site]})
    .sort_keys(lambda {|a, b| site[b] - site[a]})
    .key(lambda {|d| d[:year]})
    .sort_values(lambda {|a, b| variety[b[:variety]] - variety[a[:variety]]})

# Sizing and scales. */
w = 332
h = 132
x = pv.Scale.linear(10, 90).range(0, w)
c = pv.Colors.category10()

# The root panel. */
vis =
    .height(h * pv.keys(site).size)

# A panel per site-year. */
cell = vis.add(pv.Panel)
    .top(lambda { self.index * h})

# Title bar. */
  .text(lambda{|site| site.key});

# A dot showing the yield. */
dot = cell.add(pv.Panel)
.data(lambda {|site| site.values})
  .data(lambda {|year| year.values})
  .left(lambda {|d| x.scale(d[:yield])})
    .top(lambda {self.index * 11})
    .stroke_style(lambda {|d| c.scale(d[:year])})

# A label showing the variety. */
  .visible(lambda { self.parent.index!=0})
  .text(lambda {|d| d[:variety]})

# X-ticks. */
    .left(lambda {|d|  90+x.scale(d)})

# A legend showing the year. */
    .data([{:year=>1931}, {:year=>1932}])
    .left(lambda {|d| 260 + self.index * 40})
  .text(lambda {|d| d[:year]})


puts vis.to_svg