A box-and-whisker plot uses simple glyphs that summarize a quantitative distribution with five standard statistics: the smallest value, lower quartile, median, upper quartile, and largest value. This summary approach allows the viewer to easily recognize differences between distributions. Data from the Michelson–Morley experiment. Implementation contributed by Jason Davies. This example periodically randomizes the values to demonstrate transitions.
xxxxxxxxxx
<meta charset="utf-8">
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
/* style all box elements */
.box {
font: 10px sans-serif;
}
.box line,
.box rect,
.box circle {
fill: #fff; /*white*/
stroke: #000; /*black*/
stroke-width: 1.5px;
}
.box .center {
/* spacing of dash space pattern */
stroke-dasharray: 3,3;
}
.box .outlier {
fill: none;
stroke: #ccc; /* grey */
}
</style>
<body>
<!--load d3-->
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="box.js"></script>
<script>
var margin = {top: 10, right: 50, bottom: 20, left: 50},
width = 120 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var min = Infinity,
max = -Infinity;
var chart = d3.box()
.whiskers(iqr(1.5))
.width(width)
.height(height);
d3.csv("morley.csv", function(error, csv) {
if (error) throw error;
var data = [];
csv.forEach(function(x) {
var e = Math.floor(x.Expt - 1),
r = Math.floor(x.Run - 1),
s = Math.floor(x.Speed),
d = data[e];
if (!d) d = data[e] = [s];
else d.push(s);
if (s > max) max = s;
if (s < min) min = s;
});
chart.domain([min, max]);
var svg = d3.select("body").selectAll("svg")
.data(data)
.enter().append("svg")
.attr("class", "box")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.bottom + margin.top)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")") //moves chart up and down
.call(chart);
setInterval(function() {
svg.datum(randomize).call(chart.duration(1000));
// 1000 is the ms speed of the transition
}, 2000); //2000 is the ms duration for random events
});
function randomize(d) {
if (!d.randomizer) d.randomizer = randomizer(d);
return d.map(d.randomizer);
}
function randomizer(d) {
var k = d3.max(d) * .02;
return function(d) {
return Math.max(min, Math.min(max, d + k * (Math.random() - .5)));
};
}
// 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>
https://d3js.org/d3.v3.min.js