Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@monfera
Last active December 19, 2015 03:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monfera/8dbaabf493fbc0c4ae0c to your computer and use it in GitHub Desktop.
Save monfera/8dbaabf493fbc0c4ae0c to your computer and use it in GitHub Desktop.
Bandlines

Bandlines were invented by Stephen Few as background for sparklines to aid quick interpretation, crucial on dashboards: "Bandlines use horizontal bands of color in the background of the plot area to display information about the distribution of values. This information is similar to that found in a box plot. To do this you must gather information about how values related to the measure that will be featured in the sparkline are distributed during a period of history that usually extends further into the past than the values that will appear in the sparkline itself. [...] Bandlines may be modified to represent other meaningful ranges besides quartile-based distributions.".

The design document also describes glyphs for identifying outliers, as well as a complementary sparkstrip to show the value range bar, optionally with strip plots - transparent circles that show individual points and reveal their distribution (all shown), as well as other options.

Stephen Few provides an exceptionally detailed and pertinent guide to show how to make, as well as how to use this specific type of visualization:

Introducing Bandlines by Stephen Few

Interactive example

Larger dashboard example with article

The example tser sampler generates a lot of outliers on purpose - to make them appear regularly, and to illustrate how outliers effect the bands.

Source code

License

/**
* Bandline styling
*/
g.bandLine .band,
g.sparkStrip .band {
fill: black
}
g.bands .band.s0 {fill: rgb(247, 247, 248)}
g.bands .band.s1 {fill: rgb(224, 225, 227)}
g.bands .band.s2 {fill: rgb(188, 189, 192)}
g.bands .band.s3 {stroke: white; stroke-width: 1px; fill: none;} /* salient: hsl(120, 100%, 38%) */
g.bandLine,
g.sparkStrip {
fill: none;
}
g.bandLine .valueLine,
g.sparkStrip .valueBox,
g.sparkStrip .valuePoints,
g.bandLine .valuePoints .point.highOutlier {
stroke: black; /*rgb(226, 60, 180);*/
}
g.bandLine .valuePoints .point {
fill: black; /*rgb(226, 60, 180);*/
}
g.bandLine .valueLine {
stroke-width: 1;
}
g.sparkStrip .valueBox,
g.sparkStrip .valuePoints {
stroke-width: 0.5;
}
g.sparkStrip .valueBox,
g.bandLine .valuePoints .point.highOutlier {
fill: white;
}
/**
* Bandline renderer
*/
function defined(x) {
return !isNaN(x) && isFinite(x) && x !== null
}
function rectanglePath(xr, yr) {
return d3.svg.line()([[xr[0], yr[0]], [xr[1], yr[0]], [xr[1], yr[1]], [xr[0], yr[1]]]) + 'Z'
}
function bandLinePath(valueAccessor, xScale, yScaler, d) {
var drawer = d3.svg.line().defined(compose(defined, property(1)))
return drawer(valueAccessor(d).map(function(s, i) {return [xScale(i), yScaler(d)(s)]}))
}
function bandData(bands, yScaler, d) {
var yScale = yScaler(d)
return bands.map(function(band, i) {
return {key: i, value: band, yScale: yScale}
})
}
function renderBands(root, bands, yScaler, xRanger, yRanger) {
bind(bind(root, 'bands'), 'band', 'path', bandData.bind(0, bands, yScaler))
.transition()
.attr('class', function(d, i) {return 'band s' + i})
.attr('d', function(d) {return rectanglePath(xRanger(d), yRanger(d))})
}
function pointData(valueAccessor, d) {
return valueAccessor(d)
.map(function(value, i) {return {key: i, value: value, o: d}})
.filter(compose(defined, value))
}
function renderPoints(root, valueAccessor, pointStyleAccessor, rScale, xSpec, ySpec) {
bind(root, 'valuePoints', 'g', pointData.bind(0, valueAccessor))
.entered
.attr('transform', translate(xSpec, ySpec))
root['valuePoints']
.transition()
.attr('transform', translate(xSpec, ySpec))
bind(root['valuePoints'], 'point', 'circle')
.attr('class', function(d) {return 'point ' + pointStyleAccessor(d.value)})
.attr('r', function(d) {return rScale(pointStyleAccessor(d.value))})
root['valuePoints'].exit().remove()
}
function valuesExtent(valueAccessor, d) {
return d3.extent(valueAccessor(d).filter(defined))
}
function sparkStripBoxPath(valueAccessor, xScale, yRange, d) {
var midY = d3.mean(yRange)
var halfHeight = (yRange[1] - yRange[0]) / 2
return rectanglePath(
valuesExtent(valueAccessor, d).map(xScale),
[midY - halfHeight / 2, midY + halfHeight / 2]
)
}
function renderExtent(root, valueAccessor, xScale, yRange) {
bind(root, 'valueBox', 'path')
.transition()
.attr('d', sparkStripBoxPath.bind(0, valueAccessor, xScale, yRange))
}
function renderValueLine(root, valueAccessor, xScale, yScaler) {
bind(root, 'valueLine', 'path')
.transition()
.attr('d', bandLinePath.bind(0, valueAccessor, xScale, yScaler))
}
function bandLine() {
function renderBandLine(root) {
var bandLine = bind(root, 'bandLine')
renderBands(bandLine, _bands, _yScalerOfBandLine, constant(_xScaleOfBandLine.range()),
function(d) {return d.value.map(d.yScale)})
renderValueLine(bandLine, _valueAccessor, _xScaleOfBandLine, _yScalerOfBandLine)
renderPoints(bandLine, _valueAccessor, _pointStyleAccessor, _rScaleOfBandLine,
compose(_xScaleOfBandLine, key), function(d) {return _yScalerOfBandLine(d.o)(d.value)})
}
function renderSparkStrip(root) {
var sparkStrip = bind(root, 'sparkStrip')
renderBands(sparkStrip, _bands, _yScalerOfSparkStrip, function(d) {
return d.value.map(_xScaleOfSparkStrip)
}, constant(_yRange))
renderExtent(sparkStrip, _valueAccessor, _xScaleOfSparkStrip, _yRange)
renderPoints(sparkStrip, _valueAccessor, _pointStyleAccessor, _rScaleOfSparkStrip,
compose(_xScaleOfSparkStrip, value), _yScalerOfSparkStrip())
}
function yScalerOfBandLineCalc() {
return function(d) {
return d3.scale.linear()
.domain(valuesExtent(_valueAccessor, d))
.range(_yRange)
.clamp(true)
}
}
var _bands = [[0, 0.25], [0.25, 0.5], [0.5, 0.75], [0.75, 1]]
var bands = function(spec) {
if(spec !== void(0)) {
_bands = spec
return functionalObject
} else {
return bands
}
}
var _valueAccessor = value
var valueAccessor = function(spec) {
if(spec !== void(0)) {
_valueAccessor = spec
_yScalerOfBandLine = yScalerOfBandLineCalc()
return functionalObject
} else {
return _valueAccessor
}
}
var _xScaleOfBandLine = d3.scale.linear()
var xScaleOfBandLine = function(spec) {
if(spec !== void(0)) {
_xScaleOfBandLine = spec
return functionalObject
} else {
return _xScaleOfBandLine
}
}
var _xScaleOfSparkStrip = d3.scale.linear()
var xScaleOfSparkStrip = function(spec) {
if(spec !== void(0)) {
_xScaleOfSparkStrip = spec
return functionalObject
} else {
return _xScaleOfSparkStrip
}
}
var _rScaleOfBandLine = constant(2)
var rScaleOfBandLine = function(spec) {
if(spec !== void(0)) {
_rScaleOfBandLine = spec
return functionalObject
} else {
return _rScaleOfBandLine
}
}
var _rScaleOfSparkStrip = constant(2)
var rScaleOfSparkStrip = function(spec) {
if(spec !== void(0)) {
_rScaleOfSparkStrip = spec
return functionalObject
} else {
return _rScaleOfSparkStrip
}
}
var _yRange = [0, 1]
var _yScalerOfSparkStrip
var _yScalerOfBandLine
var yRange = function(spec) {
if(spec !== void(0)) {
_yRange = spec
_yScalerOfSparkStrip = constant(d3.mean(_yRange))
_yScalerOfBandLine = yScalerOfBandLineCalc()
return functionalObject
} else {
return _yRange
}
}
var _pointStyleAccessor = constant('normal')
var pointStyleAccessor = function(spec) {
if(spec !== void(0)) {
_pointStyleAccessor = spec
return functionalObject
} else {
return _pointStyleAccessor
}
}
var functionalObject = {
// For reference: http://bost.ocks.org/mike/chart/
renderBandLine: renderBandLine,
renderSparkStrip: renderSparkStrip,
bands: bands,
valueAccessor: valueAccessor,
xScaleOfBandLine: xScaleOfBandLine,
xScaleOfSparkStrip: xScaleOfSparkStrip,
rScaleOfBandLine: rScaleOfBandLine,
rScaleOfSparkStrip: rScaleOfSparkStrip,
yRange: yRange,
pointStyleAccessor: pointStyleAccessor
}
return functionalObject
}
function sample() {
// Sampling from a normal distribution raised to a power for frequent generation of outliers
var tserLength = 8
var range = Array.apply(Array, Array(tserLength))
var tsers = ['Insulin-like growth factor', 'Von Willebrand Factor', 'Voltage-gated 6T & 1P',
'Mechanosensitive ion ch.', 'GABAA receptor positive ', 'Epidermal growth factor',
'Signal recognition particle'].map(function(d) {
return {
key: d,
value: range.map(function() {
return (Math.random() > 0.5 ? 1 : -1) * Math.pow(Math.abs(
Math.random() + Math.random() + Math.random()
+ Math.random() + Math.random() + Math.random() - 3) / 3,
1.3)
})
}
})
return tsers
}
function constant(value) {
return function() {
return value
}
}
function compose(fun1, fun2) {
if(arguments.length === 2) {
return function(/*args*/) {
return fun1(fun2.apply(null, arguments))
}
} else {
var functions = Array.prototype.slice.call(arguments)
var len = functions.length
return function(/*args*/) {
var value = (functions[len - 1]).apply(null, arguments)
var i
for(i = Math.max(0, len - 2); i >= 0; i--) {
value = (functions[i]).call(null, value)
}
return value
}
}
}
function property(key) {
return function(thing) {
return thing[key]
}
}
function key(obj) {
return obj.key
}
function value(obj) {
return obj.value
}
function window2(a) {
return a.map(function(value, index, array) {
return [value, array[index + 1]]
}).slice(0, a.length - 1)
}
function bind0(rootSelection, cssClass, element, dataFlow) {
element = element || 'g' // fixme switch from variadic to curried
dataFlow = typeof dataFlow === 'function' ? dataFlow
: (dataFlow === void(0) ? function(d) {return [d]} : constant(dataFlow))
var binding = rootSelection.selectAll('.' + cssClass).data(dataFlow, key)
binding.entered = binding.enter().append(element)
binding.entered.classed(cssClass, true)
return binding
}
function bind(object, key) {
var result = bind0.apply(null, arguments)
object[key] = result
return result
}
function translate(funX, funY) {
return function(d, i) {
return 'translate(' + (typeof funX === 'function' ? funX(d, i) : funX) + ','
+ (typeof funY === 'function' ? funY(d, i) : funY) + ')'
}
}
function translateX(funX) {
return function(d, i) {
return 'translate(' + (typeof funX === 'function' ? funX(d, i) : funX) + ', 0)'
}
}
function translateY(funY) {
return function(d, i) {
return 'translate(0, ' + (typeof funY === 'function' ? funY(d, i) : funY) + ')'
}
}
<!DOCTYPE html>
<meta charset='utf-8'>
<style>
body {
margin-left: 160px;
margin-top: 40px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
}
.header {
font-weight: bold;
fill: #777;
}
</style>
<link href="bandline.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="du.js" type="text/javascript"></script>
<script src="data.js" type="text/javascript"></script>
<script src="model.js" type="text/javascript"></script>
<script src="bandline.js" type="text/javascript"></script>
<script defer="defer" src="render.js" type="text/javascript"></script>
<body onload="sampleAndRender()">
<svg xmlns="http://www.w3.org/2000/svg"></svg>
<div><button onclick="sampleAndRender()">Update</button></div>
</body>
Copyright (c) 2015, Robert Monfera.
Bandlines visual design: Stephen Few
http://www.perceptualedge.com/articles/visual_business_intelligence/introducing_bandlines.pdf
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of sf-student-dashboard nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function setupBandline(tsers) {
var allValuesSorted = [].concat.apply([], tsers.map(value)).sort(d3.ascending)
var bandThresholds = [
d3.min(allValuesSorted),
d3.quantile(allValuesSorted, 0.25),
d3.quantile(allValuesSorted, 0.75),
d3.max(allValuesSorted)
]
var outlierClassifications = ['lowOutlier', 'normal', 'highOutlier']
function makeOutlierScale(sortedValues) {
var iqrDistanceMultiplier = 1.5 // As per Stephen Few's specification
var iqr = [d3.quantile(sortedValues, 0.25), d3.quantile(sortedValues, 0.75)]
var midspread = iqr[1] - iqr[0]
return d3.scale.threshold()
.domain([
iqr[0] - iqrDistanceMultiplier * midspread,
iqr[1] + iqrDistanceMultiplier * midspread
])
.range(outlierClassifications)
}
function medianLineBand(sortedValues) {
// The median line is approximated as a band of 0 extent (CSS styling is via 'stroke').
// This 'band' is to be tacked on last so it isn't occluded by other bands
// (SVG uses the painter's algorithm for Z ordering).
var median = d3.median(sortedValues)
return [median, median]
}
var temporalDomain = [0, d3.max(tsers.map(compose(property('length'), property('value')))) - 1]
// Setting up the bandLine with the domain dependent values only (FP curry style applied on
// 'functional objects'). This helps decouple the Model and the viewModel (MVC-like principle).
return bandLine()
.bands(window2(bandThresholds).concat([medianLineBand(allValuesSorted)]))
.valueAccessor(property('value'))
.pointStyleAccessor(makeOutlierScale(allValuesSorted))
.xScaleOfBandLine(d3.scale.linear().domain(temporalDomain))
.xScaleOfSparkStrip(d3.scale.linear().domain(d3.extent(bandThresholds)))
.rScaleOfBandLine(d3.scale.ordinal().domain(outlierClassifications))
}
function sampleAndRender() {
var tsers = sample()
render(setupBandline(tsers), tsers)
}
function render(curriedBandLine, tsers) {
var margin = {top: 5, right: 40, bottom: 20, left: 120}
var width = 370 - margin.left - margin.right
var height = 370 - margin.top - margin.bottom
var rowPitch = 40
var rowBandRange = rowPitch / 1.3
// Column widths
var nameColumnWidth = 160
var bandLineWidth = 100
var sparkStripWidth = 50
var columnSeparation = 10
// The bandline gets augmented with the View specific settings (screen widths etc.)
var bandLine = curriedBandLine // fixme implement bandline .copy
// Augment partially set up elements
bandLine.xScaleOfBandLine().range([0, bandLineWidth])
bandLine.xScaleOfSparkStrip().range([0, sparkStripWidth])
bandLine.rScaleOfBandLine().range([2, 0, 2])
// Add new elements
bandLine
.rScaleOfSparkStrip(constant(2))
.yRange([rowBandRange / 2 , -rowBandRange / 2])
/**
* Root
*/
var svg = d3.selectAll('svg')
svg
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
var dashboard = bind(svg, 'dashboard', 'g', [{key: 0}])
/**
* Headers
*/
bind(dashboard, 'header', 'text', [{key: 'Name'}, {key: 'Time Series'}, {key: 'Spread'}])
.entered
.text(key)
.attr('transform', translate(function(d, i) {
return [0, nameColumnWidth, nameColumnWidth + bandLineWidth + 3 * columnSeparation][i]
}, rowPitch))
/**
* Rows
*/
var row = bind(dashboard, 'row', 'g', tsers)
row.attr('transform', function rowTransform(d, i) {return translateY((i + 2) * rowPitch)()})
bind(row, 'nameCellText', 'text')
.text(key)
.attr('y', '0.5em')
bind(row, 'assignmentScoresCell')
.attr('transform', translateX(nameColumnWidth + columnSeparation))
.call(bandLine.renderBandLine)
bind(row, 'assignmentScoresVerticalCell')
.attr('transform', translateX(nameColumnWidth + bandLineWidth + 2 * columnSeparation))
.call(bandLine.renderSparkStrip)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment