Skip to content

Instantly share code, notes, and snippets.

Forked from mbostock/.block
Last active April 8, 2016 22:25
Show Gist options
  • Save mbostock/3048166 to your computer and use it in GitHub Desktop.
Save mbostock/3048166 to your computer and use it in GitHub Desktop.
Duration Histogram
license: gpl-3.0

This chart shows a histogram of a log-normal distribution of time durations. The data is randomly generated: each value is a number representing a duration measured in minutes. The values are then binned at regular intervals using D3’s histogram layout. A custom tick format for the x-axis converts these numbers to dates before passing them through a d3.time.format. The x-axis uses a linear scale, such that the tick values appear in-between bars; this provides better indication that each bar represents the count of values between its surrounding tick values.

See also this histogram of an Irwin–Hall distribution.

<!DOCTYPE html>
<meta charset="utf-8">
body {
font: 10px sans-serif;
.bar rect {
fill: steelblue;
shape-rendering: crispEdges;
.bar text {
fill: #fff;
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
<script src="//"></script>
// Generate a log-normal distribution with a median of 30 minutes.
var values = d3.range(1000).map(d3.random.logNormal(Math.log(30), .4));
// Formatters for counts and times (converting numbers to Dates).
var formatCount = d3.format(",.0f"),
formatTime = d3.time.format("%H:%M"),
formatMinutes = function(d) { return formatTime(new Date(2012, 0, 1, 0, d)); };
var margin = {top: 10, right: 30, bottom: 30, left: 30},
width = 960 - margin.left - margin.right,
height = 500 - - margin.bottom;
var x = d3.scale.linear()
.domain([0, 120])
.range([0, width]);
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.y; })])
.range([height, 0]);
var xAxis = d3.svg.axis()
var svg ="body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + + margin.bottom)
.attr("transform", "translate(" + margin.left + "," + + ")");
var bar = svg.selectAll(".bar")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
.attr("x", 1)
.attr("width", x(data[0].dx) - 1)
.attr("height", function(d) { return height - y(d.y); });
.attr("dy", ".75em")
.attr("y", 6)
.attr("x", x(data[0].dx) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.y); });
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment