Create a gist now

Instantly share code, notes, and snippets.

@mbostock /.block forked from mbostock/.block
Last active Nov 17, 2016

What would you like to do?
Histogram
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar rect {
fill: steelblue;
}
.bar text {
fill: #fff;
font: 10px sans-serif;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var data = d3.range(1000).map(d3.randomBates(10));
var formatCount = d3.format(",.0f");
var svg = d3.select("svg"),
margin = {top: 10, right: 30, bottom: 30, left: 30},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleLinear()
.rangeRound([0, width]);
var bins = d3.histogram()
.domain(x.domain())
.thresholds(x.ticks(20))
(data);
var y = d3.scaleLinear()
.domain([0, d3.max(bins, function(d) { return d.length; })])
.range([height, 0]);
var bar = g.selectAll(".bar")
.data(bins)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; });
bar.append("rect")
.attr("x", 1)
.attr("width", x(bins[0].x1) - x(bins[0].x0) - 1)
.attr("height", function(d) { return height - y(d.length); });
bar.append("text")
.attr("dy", ".75em")
.attr("y", 6)
.attr("x", (x(bins[0].x1) - x(bins[0].x0)) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.length); });
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
</script>

hirokai commented Jan 9, 2015

In line 70:

    .attr("width", x(data[0].dx) - 1)

The code above gives negative width for some data I made.

Should x(data[0].dx) - 1 be x(data[0].dx) - x(0) actually?

wangxuq commented Aug 20, 2015

when I use these code to build the chart,the d3.scale.liner().domain([0,1]) cannot work, this is to say the line range cannot appear.why?
as bellow:
image

aww commented Oct 10, 2015

@hirokai made a very good point about the width computation. This version obviously works, but it doesn't generalize to cases where the x-domain doesn't start at 0. It caused me to waste a little time when I first tried to apply this example to my situation. Width should be instead x(data[0].dx) - x(0) - 1 (assuming we still want gaps between the bins).
https://gist.github.com/aww/bf245ae8d58afcebd930

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment