Box Plot

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Box Plot</title>
<script src="js/d3.js"></script>
<script src="js/box.js"></script>
<style type="text/css">
.box {
font: 10px sans-serif;
}
.box line,
.box rect,
.box circle {
fill: #fff;
stroke: #000;
stroke-width: 1.5px;
}

.box .center {
stroke-dasharray: 3,3;
}

.box .outlier {
fill: none;
stroke: #ccc;
}
</style>
</head>
<body>
<script type="text/javascript">
var arr = new Array(100);
for(var i=0;i<100; i++){
arr[i] = (Math.random() * 100).toFixed(2);
}
var min = d3.min(arr), max = d3.max(arr);

var margin = {top: 10, right: 50, bottom: 20, left: 50},
width = 200 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var box = d3.box().whiskers(iqr(1.5)).width(width).height(height);
box.domain([min, max]);
d3.select('body').append('svg').datum(arr)
.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 + ")")
.call(box);
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>
</body>
</html>
posted @ 2016-01-25 21:55  最喜欢  阅读(793)  评论(0编辑  收藏  举报