Skip to content

Instantly share code, notes, and snippets.

@ilanman
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilanman/aafe07c50860b49e6a0e to your computer and use it in GitHub Desktop.
Save ilanman/aafe07c50860b49e6a0e to your computer and use it in GitHub Desktop.
Box plots using d3 to visualize consistency NFL combine physical performances across time.
(function() {
// Inspired by http://informationandvisualization.de/blog/box-plot
d3.box = function() {
var width = 1,
height = 1,
duration = 0,
domain = null,
value = Number,
whiskers = boxWhiskers,
quartiles = boxQuartiles,
showLabels = true, // whether or not to show text labels
numBars = 4,
curBar = 1,
tickFormat = null;
// For each small multiple…
function box(g) {
g.each(function(data, i) {
//d = d.map(value).sort(d3.ascending);
//var boxIndex = data[0];
//var boxIndex = 1;
var d = data[1].sort(d3.ascending);
var g = d3.select(this),
n = d.length,
min = d[0],
max = d[n - 1];
// Compute quartiles. Must return exactly 3 elements.
var quartileData = d.quartiles = quartiles(d);
// Compute whiskers. Must return exactly 2 elements, or null.
var whiskerIndices = whiskers && whiskers.call(this, d, i),
whiskerData = whiskerIndices && whiskerIndices.map(function(i) { return d[i]; });
// Compute outliers. If no whiskers are specified, all data are "outliers".
// We compute the outliers as indices, so that we can join across transitions!
var outlierIndices = whiskerIndices
? d3.range(0, whiskerIndices[0]).concat(d3.range(whiskerIndices[1] + 1, n))
: d3.range(n);
// Compute the new x-scale.
var x1 = d3.scale.linear()
.domain(domain && domain.call(this, d, i) || [min, max])
.range([height, 0]);
// Retrieve the old x-scale, if this is an update.
var x0 = this.__chart__ || d3.scale.linear()
.domain([0, Infinity])
// .domain([0, max])
.range(x1.range());
// Stash the new scale.
this.__chart__ = x1;
// Note: the box, median, and box tick elements are fixed in number,
// so we only have to handle enter and update. In contrast, the outliers
// and other elements are variable, so we need to exit them! Variable
// elements also fade in and out.
// Update center line: the vertical line spanning the whiskers.
var center = g.selectAll("line.center")
.data(whiskerData ? [whiskerData] : []);
//vertical line
center.enter().insert("line", "rect")
.attr("class", "center")
.attr("x1", width / 2)
.attr("y1", function(d) { return x0(d[0]); })
.attr("x2", width / 2)
.attr("y2", function(d) { return x0(d[1]); })
.style("opacity", 1e-6)
.transition()
.duration(duration)
.style("opacity", 1)
.attr("y1", function(d) { return x1(d[0]); })
.attr("y2", function(d) { return x1(d[1]); });
center.transition()
.duration(duration)
.style("opacity", 1)
.attr("y1", function(d) { return x1(d[0]); })
.attr("y2", function(d) { return x1(d[1]); });
center.exit().transition()
.duration(duration)
.style("opacity", 1e-6)
.attr("y1", function(d) { return x1(d[0]); })
.attr("y2", function(d) { return x1(d[1]); })
.remove();
// Update innerquartile box.
var box = g.selectAll("rect.box")
.data([quartileData]);
box.enter().append("rect")
.attr("class", "box")
.attr("x", 0)
.attr("y", function(d) { return x0(d[2]); })
.attr("width", width)
.attr("height", function(d) { return x0(d[0]) - x0(d[2]); })
.transition()
.duration(duration)
.attr("y", function(d) { return x1(d[2]); })
.attr("height", function(d) { return x1(d[0]) - x1(d[2]); });
box.transition()
.duration(duration)
.attr("y", function(d) { return x1(d[2]); })
.attr("height", function(d) { return x1(d[0]) - x1(d[2]); });
// Update median line.
var medianLine = g.selectAll("line.median")
.data([quartileData[1]]);
medianLine.enter().append("line")
.attr("class", "median")
.attr("x1", 0)
.attr("y1", x0)
.attr("x2", width)
.attr("y2", x0)
.transition()
.duration(duration)
.attr("y1", x1)
.attr("y2", x1);
medianLine.transition()
.duration(duration)
.attr("y1", x1)
.attr("y2", x1);
// Update whiskers.
var whisker = g.selectAll("line.whisker")
.data(whiskerData || []);
whisker.enter().insert("line", "circle, text")
.attr("class", "whisker")
.attr("x1", 0)
.attr("y1", x0)
.attr("x2", 0 + width)
.attr("y2", x0)
.style("opacity", 1e-6)
.transition()
.duration(duration)
.attr("y1", x1)
.attr("y2", x1)
.style("opacity", 1);
whisker.transition()
.duration(duration)
.attr("y1", x1)
.attr("y2", x1)
.style("opacity", 1);
whisker.exit().transition()
.duration(duration)
.attr("y1", x1)
.attr("y2", x1)
.style("opacity", 1e-6)
.remove();
// Update outliers.
var outlier = g.selectAll("circle.outlier")
.data(outlierIndices, Number);
outlier.enter().insert("circle", "text")
.attr("class", "outlier")
.attr("r", 5)
.attr("cx", width / 2)
.attr("cy", function(i) { return x0(d[i]); })
.style("opacity", 1e-6)
.transition()
.duration(duration)
.attr("cy", function(i) { return x1(d[i]); })
.style("opacity", 1);
outlier.transition()
.duration(duration)
.attr("cy", function(i) { return x1(d[i]); })
.style("opacity", 1);
outlier.exit().transition()
.duration(duration)
.attr("cy", function(i) { return x1(d[i]); })
.style("opacity", 1e-6)
.remove();
// Compute the tick format.
var format = tickFormat || x1.tickFormat(8);
// Update box ticks.
var boxTick = g.selectAll("text.box")
.data(quartileData);
if(showLabels == true) {
boxTick.enter().append("text")
.attr("class", "box")
.attr("dy", ".3em")
.attr("dx", function(d, i) { return i & 1 ? 6 : -6 })
.attr("x", function(d, i) { return i & 1 ? + width : 0 })
.attr("y", x0)
.attr("text-anchor", function(d, i) { return i & 1 ? "start" : "end"; })
.text(format)
.transition()
.duration(duration)
.attr("y", x1);
}
boxTick.transition()
.duration(duration)
.text(format)
.attr("y", x1);
// Update whisker ticks. These are handled separately from the box
// ticks because they may or may not exist, and we want don't want
// to join box ticks pre-transition with whisker ticks post-.
var whiskerTick = g.selectAll("text.whisker")
.data(whiskerData || []);
if(showLabels == true) {
whiskerTick.enter().append("text")
.attr("class", "whisker")
.attr("dy", ".3em")
.attr("dx", 6)
.attr("x", width)
.attr("y", x0)
.text(format)
.style("opacity", 1e-6)
.transition()
.duration(duration)
.attr("y", x1)
.style("opacity", 1);
}
whiskerTick.transition()
.duration(duration)
.text(format)
.attr("y", x1)
.style("opacity", 1);
whiskerTick.exit().transition()
.duration(duration)
.attr("y", x1)
.style("opacity", 1e-6)
.remove();
});
d3.timer.flush();
}
box.width = function(x) {
if (!arguments.length) return width;
width = x;
return box;
};
box.height = function(x) {
if (!arguments.length) return height;
height = x;
return box;
};
box.tickFormat = function(x) {
if (!arguments.length) return tickFormat;
tickFormat = x;
return box;
};
box.duration = function(x) {
if (!arguments.length) return duration;
duration = x;
return box;
};
box.domain = function(x) {
if (!arguments.length) return domain;
domain = x == null ? x : d3.functor(x);
return box;
};
box.value = function(x) {
if (!arguments.length) return value;
value = x;
return box;
};
box.whiskers = function(x) {
if (!arguments.length) return whiskers;
whiskers = x;
return box;
};
box.showLabels = function(x) {
if (!arguments.length) return showLabels;
showLabels = x;
return box;
};
box.quartiles = function(x) {
if (!arguments.length) return quartiles;
quartiles = x;
return box;
};
return box;
};
function boxWhiskers(d) {
return [0, d.length - 1];
}
function boxQuartiles(d) {
return [
d3.quantile(d, .25),
d3.quantile(d, .5),
d3.quantile(d, .75)
];
}
})();
Y2003 Y2004 Y2005 Y2006 Y2007 Y2008 Y2009 Y2010 Y2011 Y2012 Y2013
31.5 32 35 38.5 35.5 30.5 34.5 36.5 41.5 35 32
36 38.5 40 31.5 34 29.5 37 32.5 30 36 32
31.5 34.5 34.5 31.5 35.5 33.5 41.5 35 33.5 33 35.5
32.5 40 30 33 36.5 36 36 36 29 38 31.5
37 30.5 34 36 34 30.5 32 40 37 33 33.5
38 33.5 34 35 30 34 39.5 33 29 37 35
34 34.5 34 35 36 33 37 33 34 32 32
33.5 37.5 38 33 30 30.5 34 38 35 35 39
35.5 38 36 34.5 38 28 34 41 37.5 37 33.5
34 31.5 33.5 32.5 37 35 33 36 34 35 34
34 35 38 30.5 34.5 33.5 35 36 36 36 38.5
31 32.5 35 35.5 28 36 35.5 36.5 35 31.5
34 31 33 31 33 33.5 35.5 36.5 33 30.5
31 37 32 38.5 25.5 35.5 36 35 35 32.5
34 35 36.5 35.5 33.5 35 36.5 31.5 33 33.5
33.5 36 35 31.5 31 36 36 38 36 32.5
30.5 33.5 32.5 38 34 40 36.5 34.5 31 37.5
30 34 30.5 34 31.5 34 38.5 37.5 34 35
33.5 35.5 40.5 32.5 36 30.5 34.5 36 29
32 35.5 32.5 37 36 36 31 31
38.5 34 33.5 33 40.5 33 40.5 30.5
33 31.5 32 33.5 32 34 36 31.5
35.5 36.5 33.5 34.5 30 34
30 34 41 43
34 34.5 36
38 38 30
34 35
32.5 32
40 34
33
30
35.5
35
34.5
37.5
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.box {
font: 10px sans-serif;
}
.box line,
.box rect,
.box circle {
fill: steelblue;
stroke: #000;
stroke-width: 1px;
}
.box .center {
stroke-dasharray: 3,3;
}
.box .outlier {
fill: none;
stroke: #000;
}
.axis {
font: 12px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.d3-tip {
font-weight: bold;
background: rgba(0, 0, 0, 0.8);
padding: 12px;
color: #fff;
z-index: 5070;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="box.js"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<script>
var labels = true; // show the text labels beside individual boxplots?
var margin = {top: 30, right: 50, bottom: 90, left: 50};
var width = 800 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;
var min = Infinity,
max = -Infinity;
var tip = d3.tip()
.attr('class', 'd3-tip')
.style("visibility","visible")
.offset([-20, 0])
.html(function(d) {
return "Hello" + d;
});
// parse in the data
d3.csv("data.csv", function(error, csv) {
// using an array of arrays with
// data[n][2]
// where n = number of columns in the csv file
// data[i][0] = name of the ith column
// data[i][1] = array of values of ith column
var data = [];
data[0] = [];
data[1] = [];
data[2] = [];
data[3] = [];
data[4] = [];
data[5] = [];
data[6] = [];
data[7] = [];
data[8] = [];
data[9] = [];
data[10] = [];
// add more rows if your csv file has more columns
// add here the header of the csv file
data[0][0] = "Y2003";
data[1][0] = "Y2004";
data[2][0] = "Y2005";
data[3][0] = "Y2006";
data[4][0] = "Y2007";
data[5][0] = "Y2008";
data[6][0] = "Y2009";
data[7][0] = "Y2010";
data[8][0] = "Y2011";
data[9][0] = "Y2012";
data[10][0] = "Y2013";
// add more rows if your csv file has more columns
data[0][1] = [];
data[1][1] = [];
data[2][1] = [];
data[3][1] = [];
data[4][1] = [];
data[5][1] = [];
data[6][1] = [];
data[7][1] = [];
data[8][1] = [];
data[9][1] = [];
data[10][1] = [];
csv.forEach(function(d) {
var v1 = Math.floor(d.Y2003),
v2 = Math.floor(d.Y2004);
v3 = Math.floor(d.Y2005),
v4 = Math.floor(d.Y2006);
v5 = Math.floor(d.Y2007);
v6 = Math.floor(d.Y2008);
v7 = Math.floor(d.Y2009);
v8 = Math.floor(d.Y2010);
v9 = Math.floor(d.Y2011);
v10 = Math.floor(d.Y2012);
v11 = Math.floor(d.Y2013);
v1m=v1;
v2m=v2;
v3m=v3;
v4m=v4;
v5m=v5;
v6m=v6;
v7m=v7;
v8m=v8;
v9m=v9;
v10m=v10;
v11m=v11;
if(v1m==0){
v1m=1000;
} else {
v1m=v1;
data[0][1].push(v1);
};
if(v2m==0){
v2m=1000;
} else {
v2m=v2;
data[1][1].push(v2);
};
if(v3m==0){
v3m=1000;
} else {
v3m=v3;
data[2][1].push(v3);
};
if(v4m==0){
v4m=1000;
} else {
v4m=v4;
data[3][1].push(v4);
};
if(v5m==0){
v5m=1000;
} else {
v5m=v5;
data[4][1].push(v5);
};
if(v6m==0){
v6m=1000;
} else {
v6m=v6;
data[5][1].push(v6);
};
if(v7m==0){
v7m=1000;
} else {
v7m=v7;
data[6][1].push(v7);
};
if(v8m==0){
v8m=1000;
} else {
v8m=v8;
data[7][1].push(v8);
};
if(v9m==0){
v9m=1000;
} else {
v9m=v9;
data[8][1].push(v9);
};
if(v10m==0){
v10m=1000;
} else {
v10m=v10;
data[9][1].push(v10);
};
if(v11m==0){
v11m=1000;
} else {
v11m=v11;
data[10][1].push(v11);
};
var rowMax = Math.max(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11)*1.05;
var rowMin = Math.min(v1m, v2m, v3m, v4m, v5m, v6m, v7m, v8m, v9m, v10m, v11m)*0.95;
if (rowMax > max) max = rowMax;
if (rowMin < min) min = rowMin;
});
var chart = d3.box()
.whiskers(iqr(1.5))
.height(height)
.domain([min, max])
.showLabels(labels);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("class", "box")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// the x-axis
var x = d3.scale.ordinal()
.domain( data.map(function(d) { return d[0] } ) )
.rangeRoundBands([0 , width], 0.7, 0.3);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// the y-axis
var y = d3.scale.linear()
.domain([min, max])
.range([height + margin.top, 0 + margin.top]);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// draw the boxplots
svg.selectAll(".box")
.data(data)
.enter().append("g")
.attr("transform", function(d) { return "translate(" + x(d[0]) + "," + margin.top + ")"; } )
.call(chart.width(x.rangeBand()));
// add a title
svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 + (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "18px")
.text("Running Back Vertical");
// draw y axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text") // and text1
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("font-size", "16px")
.text("Inches");
// draw x axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height + margin.top + 10) + ")")
.call(xAxis)
.append("text") // text label for the x axis
.attr("x", (width / 2) )
.attr("y", 26 )
.attr("dy", ".71em")
.style("text-anchor", "middle")
.style("font-size", "16px")
.text("Year");
});
// Returns a function to compute the interquartile range.
function iqr(k) {
return function(d, i) {
var q1 = d.quartiles[0],
q3 = d.quartiles[2],
iqr = (q3 - q1) * k,
i = -1,
j = d.length;
while (d[++i] < q1 - iqr);
while (d[--j] > q3 + iqr);
return [i, j];
};
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment