Created
May 16, 2013 17:30
-
-
Save dangets/5593485 to your computer and use it in GitHub Desktop.
simple d3.js histogram with specified threshold bins
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script src="http://mbostock.github.com/d3/d3.v2.js"></script> | |
</head> | |
<body> | |
<svg id="viz"> | |
</svg> | |
<script type="text/javascript"> | |
var w = 500; | |
var h = 400; | |
var inputData = [ | |
0.1, 0.2, 0.3, 0.4, 0.8, // bin 1 | |
1.1, 1.2, 1.3, // bin 2 | |
2.1, 2.2, 2.3, 2.7, 2.8, // bin 3 | |
3.1, 3.2, 3.3, 3.4, // bin 4 | |
4.1, 4.2, 4.3, 4.8, 4.9, // bin 5 | |
]; | |
var dataRange = [0.1, 4.5]; | |
var histBins = d3.range(0, 6); | |
var hist = d3.layout.histogram() | |
.range(dataRange) | |
.bins(histBins); | |
var histData = hist(inputData); | |
var histMax = d3.max(histData, function(d) { return d.y; }); | |
console.debug(histBins); | |
console.debug(histData); | |
console.debug(histMax); | |
var svg = d3.select("#viz") | |
.attr("width", w) | |
.attr("height", h); | |
var xScale = d3.scale.linear() | |
.domain([histBins[0], histBins[histBins.length-1]]) | |
.range([0, w]); | |
var yScale = d3.scale.linear() | |
.domain([0, histMax]) | |
.range([0, h]); | |
var barWidth = w / histBins.length; | |
var bars = svg.selectAll(".bar") | |
.data(histData); | |
var barEnter = bars.enter() | |
.append("g") | |
.attr("class", "bar") | |
.attr("transform", function(d) { return "translate(" + xScale(d.x) + ", 0)"; }); | |
barEnter.append("rect") | |
.attr("y", function(d) { return h - yScale(d.y); }) | |
.attr("width", barWidth) | |
.attr("height", function(d) { return 1 + yScale(d.y); }) | |
.attr("fill", "steelblue"); | |
barEnter.append("text") | |
.attr("x", barWidth / 2) | |
.attr("y", h - 15) | |
.text(function(d) { return String(d.x); }); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment