public
Last active

Histogram (Redirect)

  • Download Gist
index.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
<!DOCTYPE html>
<html>
<head>
<title>Histogram</title>
<script type="text/javascript" src="https://github.com/mbostock/d3/raw/v1.17.0/d3.js"></script>
<script type="text/javascript" src="https://github.com/mbostock/d3/raw/v1.17.0/d3.layout.js"></script>
<style type="text/css">
body {
font: 10px sans-serif;
}
rect {
fill: steelblue;
stroke: white;
}
line {
stroke: black;
shape-rendering: crispEdges;
}
</style>
</head>
<body>
<script type="text/javascript">
var n = 10000, // number of trials
m = 10, // number of random variables
data = [];
// Generate an Irwin-Hall distribution.
for (var i = 0; i < n; i++) {
for (var s = 0, j = 0; j < m; j++) {
s += Math.random();
}
data.push(s);
}
var w = 400,
h = 400;
var histogram = d3.layout.histogram()
(data);
var x = d3.scale.ordinal()
.domain(histogram.map(function(d) { return d.x; }))
.rangeRoundBands([0, w]);
var y = d3.scale.linear()
.domain([0, d3.max(histogram, function(d) { return d.y; })])
.range([0, h]);
var vis = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("transform", "translate(.5)");
vis.selectAll("rect")
.data(histogram)
.enter().append("svg:rect")
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + (h - y(d.y)) + ")"; })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.y); })
.attr("height", 0)
.transition()
.duration(750)
.attr("y", 0)
.attr("height", function(d) { return y(d.y); });
vis.append("svg:line")
.attr("x1", 0)
.attr("x2", w)
.attr("y1", h)
.attr("y2", h);
</script>
</body>
</html>

Do you know why when I copy this code I get Uncaught ReferenceError: w is not defined (line 64) ... ?

I'm not sure, but try the d3-js Google group if you'd like help.

Mike

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.